Does MongoDB update an index when array elements are only reordered?

I’m working with a collection where documents contain an array of subdocuments, for example:

{
  "_id": 1,
  "tasks": [
    { "priority": 2, "dueDate": "2025-09-01" },
    { "priority": 1, "dueDate": "2025-08-20" }
  ]
}

I have an index on the array field, e.g.:

db.collection.createIndex({ "tasks.priority": 1 })

Now suppose I use an aggregation update to sort the array in place:

db.collection.updateOne(
  { _id: 1 },
  [
    {
      $set: {
        tasks: {
          $sortArray: { input: "$tasks", sortBy: { priority: 1, dueDate: 1 } }
        }
      }
    }
  ]
)

This changes the document to:

{
  "_id": 1,
  "tasks": [
    { "priority": 1, "dueDate": "2025-08-20" },
    { "priority": 2, "dueDate": "2025-09-01" }
  ]
}

From my perspective, the “first element” is now different.

My question:

  • Does MongoDB consider this a modification that requires updating the index?

  • Or since the set of values [1, 2] for tasks.priority hasn’t changed, does MongoDB skip reindexing?

  • Would the answer change if I had a compound multikey index, e.g. { “tasks.priority”: 1, “tasks.dueDate”: 1 }?

Hey mate,
this comes down to how multikey indexes work in MongoDB.

  • When you index tasks.priority, MongoDB creates separate index entries for each element in the array.Example for your doc:
{ "_id": 1, "tasks.priority": 2 }
{ "_id": 1, "tasks.priority": 1 }

→ The index stores {1, 2} regardless of array order.

  • Since $sortArray only changes the order of elements, not the set of values, the index entries don’t change.➝ MongoDB does not need to update/reindex in this case. The index is valid.
  • If you create:
db.collection.createIndex({ "tasks.priority": 1, "tasks.dueDate": 1 })

then MongoDB creates index keys per array element pair, e.g.:

(priority=2, dueDate=2025-09-01)
(priority=1, dueDate=2025-08-20)

Again, sorting doesn’t change the pairs, so the index entries remain the same.➝ No reindexing needed.

  • Only if you change, add, or remove array elements (e.g., modify a priority or dueDate value, push/pop a task). Pure reordering isn’t considered a modification that affects the index.
2 Likes

We are sure that the index will be the same after sorting the array, but the key question is whether Mongo can anticipate this and therefore save the reindexing process, or whether it will carry out the reindexing of the index even though the result will be the same. Is there any place in the Mongo documentation that supports your claim?

1 Like