Search code examples
mongodbmongodb-compass

MongoDB: How to reorder document Fields that got jumbled in the past


My DB has many documents with mostly random field order as displayed in Mongo Compass. The first field is always _id but the rest of the fields could be in any order. This makes scanning records by eye very difficult. I have read that this reordering due to upserts no longer happens with Mongo 4.2 and I have upgraded - but the problem remains. Is there a way for me to reorder my fields so each document in a collection has the same field order - say -id first then a-z?


Solution

  • You can use $replaceWith to do this. https://mongoplayground.net/p/VBzpabZuJpy

    db.YOURCOLLECTION.updateMany({}, [
      {$replaceWith: {
        $mergeObjects: [
          {
            "fieldA": "$fieldA",
            "fieldB": "$fieldB",
            "fieldC": "$fieldC",
            "fieldD": "$fieldD",
            "fieldE": "$fieldE"
          },
          "$$ROOT"
        ]
      }}
    ])