Updating documents

To update a document, we use the updateOne or updateMany methods. For example, let's update the ranking property of the Peru team. Execute the following code:

> db.teams.updateOne({"code": "PER"}, {$set: {"ranking": 1}})

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

The syntax looks a little weird, but it is not. The first question you might have is why do we need $set? We need $set to specify the fields that we are interested to update. Otherwise, you will replace the document. Consider this example:

First, let's list our teams' collection to see the first update reflected:

> db.teams.find({"code": "PER"})

{ "_id" : ObjectId("5a5cf1419afc8af268b9bb21"), "code" : "PER", "name" : "Peru", "ranking" : 1, "captain" : "Paolo Guerreo", "Trainer" : "Ricardo Gareca", "confederation" : "Conmebol" }

Also, yes, the ranking field has been updated to 1. Now let's try to update this document without the $set operator:

> db.teams.updateOne({"code": "PER"}, {"ranking": 1})

[thread1] Error: the update operation document must contain atomic operators :

Note that an error is thrown and no changes have been made. That is helpful for us because we are using the updateOne method, but there is another method called update, which will give us headaches if we don't use it properly. For example, run the following code:

> db.teams.update({"code": "PER"}, {"ranking": 1})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

At this moment, when you note that you forgot the $set operator, you have lost your team's data. Try to find the Peru team:

> db.teams.find({"code": "PER"})

No results are shown. Now a tear might be rolling down your cheek. Funny, right?

Be careful when you are updating or deleting documents. A production error of this type can cost you the post.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset