Does MongoDB skip index updates if a field is set to its current value?

I’m working with MongoDB and have a question about how updates interact with indexes. Suppose I have a document with an indexed field, and I perform an update that sets this field to the same value it already has, like so:

db.collection.updateOne(
  { _id: someId },
  { $set: { indexedField: currentValue } }
);

Will MongoDB detect that the value hasn’t changed and skip updating the index, or will it still perform index writes even if the value is identical?

In other words, is there any built-in optimization to avoid unnecessary index updates for no-op updates, or should I handle this manually in application logic?

Context:

  • MongoDB version: 7.x (or specify your version)

  • Storage engine: WiredTiger

  • Field indexedField is part of a B-tree index

Any insights into the internal behavior or best practices for minimizing unnecessary index writes would be appreciated.

Hi, yes MongoDB detects when values have not changed and skips the write entirely when the document is the same. However, if you update another unindexed field with a new value, it will write the document because that part has changed, but it will still skip the write to the index where the value remained unchanged.

1 Like

@Franck_Pachot1 Thanks for the reply.

  1. What if the write query is more complex and dynamic, involving $map, $mergeObjects, and $switch?

  2. Also, what if the write query replaces an entire embedded document with another document?

Is MongoDB also able to detect when the indexed values have not changed and skip those writes?

Yes, I think it is detected in all these cases. MongoDB applies the updates to generate a new version of the document, in memory, and compares it to the previous one, so it doesn’t depend on the operations, but on the state (same datatype, same values).

The best is to test, for example in a lab with db.setLogLevel(1, "write") and look at "keysInserted","keysDeleted","nModified" in the log. It’s a great question, I’ll write a blog post to explain.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.