MongoDB Update Collection

In mongoDB we can update a collection by two ways:-
1) Update() method:- The update () method is used when we need to update the values ​​of an existing document.
2) Save() method:-The save () method is used to replace an existing document with the document that has been passed into it.

Updating Document using update() method

The syntax of the Updating Document is −

 
\\Syntax of the Updating Document
db.collection_name.update(criteria, update_data)


Updating Document Example :

The Example of the Updating Document is −

\\Example of Updating Document in MongoDB using update() method
> db.got.find().pretty()
{
"_id" : ObjectId("59bd2e73ce524b733f14dd65"),
"name" : "Oliver Stark",
"age" : 23
}
{
"_id" : ObjectId("59bd2e8bce524b733f14dd66"),
"name" : "Jack Varys",
"age" : 29
}
{
"_id" : ObjectId("59bd2e9fce524b733f14dd67"),
"name" : "Ethan Drogo",
"age" : 26
}
{
"_id" : ObjectId("59bd2ec5ce524b733f14dd68"),
"name" : "Jackson Snow",
"age" : 24
}
-------------------
-------------------
\\update the name of Oliver Stark with the name "Noah Stark"
db.got.update({"name":"Oliver Stark"},{$set:{"name":"Noah Stark"}})
-------------------
-------------------
> db.got.find().pretty()
{
"_id" : ObjectId("59bd2e73ce524b733f14dd65"),
"name" : "Noah Stark",
"age" : 23
}
{
"_id" : ObjectId("59bd2e8bce524b733f14dd66"),
"name" : "Jack Varys",
"age" : 29
}
{
"_id" : ObjectId("59bd2e9fce524b733f14dd67"),
"name" : "Ethan Drogo",
"age" : 26
}
{
"_id" : ObjectId("59bd2ec5ce524b733f14dd68"),
"name" : "Jackson Snow",
"age" : 24
}


Updating Document using save() method

The syntax of the Updating Document is −

 
\\Syntax of the Updating Document using save()
db.collection_name.save( {_id:ObjectId(), new_document} )


Updating Document Example :

The Example of the Updating Document is −

Note:-One very important thing to note is that when you do not provide the _id field when using save() Method, then it called insert() method and the passed document is inserted into the collection as a new document.

\\Example of Updating Document in MongoDB using save() method
> db.got.save({"_id" : ObjectId("59bd2e73ce524b733f14dd65"), "name":
"Oliver Stark", "age": 30})
-------------------
-------------------
\\You should see this output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })






Visit :


Discussion



* You must be logged in to add comment.