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:
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.
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.