Monday, September 16, 2019

MongoDB Update Documents

MongoDB Update Documents

Here we are going to learn MongoDB update document.

To update documents in MongoDB, we use $set to update documents and also use _id to update a specific document.

For Example:
Suppose I want to update age where _id is 5c4f5481e71c8c1ef47e2f83,

{“_id” : ObjectId(“5c4f5481e71c8c1ef47e2f83”)}, {$set:{“age”:”18″}}

After execute above command, result will display
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })

Here, It is not mandatory to use _id to update documents. We can also use any of the key to update documents.

For Example:
Suppose I want to update age where city is Delhi,

{“city” : “Delhi”}, {$set:{“age”:”18″}}

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

The above query will always update only first document whose city will be Delhi. But suppose we have more than one document whose city is Delhi and we want to update in one shot then we have to use one more option named multi, it should be true. By default, its value become false. So in this case our query structure will be:

{“city” : “Delhi”}, {$set:{“age”:”23″}},
{multi : true}

Above query result will be:
WriteResult({ “nMatched” : 2, “nUpserted” : 0, “nModified” : 2 })

Here is showing nMatched is 2 means two data matched whose city is Delhi & nModified is 2 means, two data has been updated.

One more way to update document using save command. In this command, we pass whole JSON into save command and update any value.

For Example:
Suppose, we want to update course BBA of a document, then query will be
“_id” : ObjectId(“5c4f5481e71c8c1ef47e2f80”),
“name” : “gagandeep”,
“email” : “”,
“contact” : “7856231549”,
“city” : “Saharanpur”,
“state” : “UP”,
“course” : “BCA”,
“dept” : “IT”,
“age” : “28”

Above query will search the given _id in whole documents. If it is matched then it will update the course of that document into BBA. It means, if result will be:

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

It means, one document matched and update that document. But If its not matched, it will insert a new document with these data. It means, if result will be:

“nMatched” : 0,
“nUpserted” : 1,
“nModified” : 0,
“_id” : ObjectId(“5c4f5481e71c8c1ef47e2f84”)

It means, new document has been inserted.

No comments:

Post a Comment

Copyright © 2019 Tech Location BD. All Right Reserved