How does MongoDB's Update () method work?

Consider that mycol collectioin has the following data.

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

      

Let's update the document.

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

      

This updates the document.

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

      

Now when I try to find documents in mine collection

I see that the first document is being updated. I am confused about how updation works in mongodb

, when there is duplication of documents

.

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

      

+3


source to share


1 answer


When multiple documents meet the criteria update

, only the first matching document is updated, if not used multi

:



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

      

+2


source







All Articles