Updating data in MongoDB


To update data in MongoDB, use update(). Let us create a collection with documents −

> db.demo110.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2eeb949fd5fd66da21447b")
}
> db.demo110.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2eeb9f9fd5fd66da21447c")
}
> db.demo110.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2eeba39fd5fd66da21447d")
}

Display all documents from a collection with the help of find() method −

> db.demo110.find();

This will produce the following output −

{ "_id" : ObjectId("5e2eeb949fd5fd66da21447b"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2eeb9f9fd5fd66da21447c"), "Name" : "David" }
{ "_id" : ObjectId("5e2eeba39fd5fd66da21447d"), "Name" : "Bob" }

Following is the query to update data in MongoDB −

>db.demo110.update({_id:ObjectId("5e2eeb9f9fd5fd66da21447c")},{$set:{"Name":"Robert"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo110.find();

This will produce the following output −

{ "_id" : ObjectId("5e2eeb949fd5fd66da21447b"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2eeb9f9fd5fd66da21447c"), "Name" : "Robert" }
{ "_id" : ObjectId("5e2eeba39fd5fd66da21447d"), "Name" : "Bob" }

Updated on: 30-Mar-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements