If in my code I'm updating a document in mongoDB, is it better to check if indexed fields changed and update them only if changed (there are other fields that we should update anyway), or there'll be no effect on saving indexed fields to the existing value? does mongo immediately will update the index, or if it sees that nothing actually changed it wont try to update the index?
update operation is changing value and its index only if the value is different. example:
PRIMARY> db.test.find()
{ "_id" : ObjectId("61eef83f6b9fd30eb14ad43b"), "test" : 1 }
PRIMARY> db.test.update({test:1},{$set:{test:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
As you can see nModified: 0 and in the oplog nothing appear meaning that the operation do not have any effect ...
If the value is different it will be updated imeediately also in the index ...