Update a field to its current value

Given:

db.books.insertOne(
   {
    "_id" : 1,
    "item" : "XYZ123",
    "stock" : 15
   }
);

with an index on item.
What happens with the index and the document when I perform:

db.books.update(
   { _id: 1 },
   {
      $set: { item: "XYZ123" }, // same value !
      $setOnInsert: { stock: 10 }
   },
   { upsert: true }
)

Does mongodb recognize that nothing has changed? Or get document as well as index, or at least one of them updated and I should try to avoid such a query if possible?

Hi @Jens_Lippmann ,

If the updated dcoument does not change any values the update will only use the read required to perform it…

You can test that and compare the result document from the update:

db.test12.updateOne({x:1},{$set : {x: 1}})
{ acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 0,
  upsertedCount: 0 }

As you can see although x:1 was matched for the update the number of modified documents was 0…

Ty
Pavel

1 Like

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