Mathew
Mathew

Reputation: 231

How does MongoDB Update() method work?

Consider the mycol collectioin has following data.

{ "_id" : ObjectId("544946347db27ca99e20a95f"), "title" : "MongoDB Overview" }
{ "_id" : ObjectId("544946357db27ca99e20a960"), "title" : "MongoDB Overview" }
{ "_id" : ObjectId("544946377db27ca99e20a961"), "title" : "MongoDB Overview" }

Let us update the document.

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})

Which results in updation of the document.

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.mycol.find();

Now when i try to find the docs in my collection, i see that the first document getting updated. I am confused on how the updation works in mongodb when there is a duplication of documents.

{ "_id" : ObjectId("544946347db27ca99e20a95f"), "title" : "New MongoDB Tutorial" }
{ "_id" : ObjectId("544946357db27ca99e20a960"), "title" : "MongoDB Overview" }
{ "_id" : ObjectId("544946377db27ca99e20a961"), "title" : "MongoDB Overview" }

Upvotes: 3

Views: 442

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

When multiple documents match the update criteria, only the first matching document is updated unless the multi option is used:

db.mycol.update(
  {'title': 'MongoDB Overview'},
  {$set: {'title': 'New MongoDB Tutorial'}},
  {multi: true})

Upvotes: 2

Related Questions