MongoDB Update Document
Use db.collection.update() method to update document in MongoDB database.
Syntax:
> db.users.update(CONDITION, UPDATED DATA, OPTIONS)
Find Current Document
First find the current document in collection with user_name = rahul. We have already inserted documents in previous tutorial like below.
> db.users.find().pretty({"user_name":"rahul"})
{
"_id" : ObjectId("59a7aef2de55e8e213bf3f26"),
"id" : 1001,
"user_name" : "rahul",
"name" : [
{
"first_name" : "Rahul"
},
{
"middle_name" : ""
},
{
"last_name" : "Kumar"
}
],
"email" : "[email protected]",
"designation" : "Founder and CEO",
"location" : "India"
}
Update Document
Now change location from India to Australia for the document where id = 1001.
> db.users.update({"id":1001},{$set:{'location':'Australia'}})
Output: WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })