Syntax error Fastest way of updating in MongoDB is update() or save()?

Fastest way of updating in MongoDB is update() or save()?



The fastest way of updating is update(). Let us create a collection with documents and see how update() works −

> db.demo320.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50ee51f8647eb59e562066")
}
> db.demo320.insertOne({"Name":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50ee55f8647eb59e562067")
}
> db.demo320.insertOne({"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50ee59f8647eb59e562068")
}
> db.demo320.insertOne({"Name":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50ee5bf8647eb59e562069")
}

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

> db.demo320.find();

This will produce the following output −

{ "_id" : ObjectId("5e50ee51f8647eb59e562066"), "Name" : "Chris" }
{ "_id" : ObjectId("5e50ee55f8647eb59e562067"), "Name" : "Robert" }
{ "_id" : ObjectId("5e50ee59f8647eb59e562068"), "Name" : "Mike" }
{ "_id" : ObjectId("5e50ee5bf8647eb59e562069"), "Name" : "Sam" }

Following is the query to update() −

> db.demo320.update({Name:"Mike"},{$set:{Name:"Bob"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo320.find();

This will produce the following output −

{ "_id" : ObjectId("5e50ee51f8647eb59e562066"), "Name" : "Chris" }
{ "_id" : ObjectId("5e50ee55f8647eb59e562067"), "Name" : "Robert" }
{ "_id" : ObjectId("5e50ee59f8647eb59e562068"), "Name" : "Bob" }
{ "_id" : ObjectId("5e50ee5bf8647eb59e562069"), "Name" : "Sam" }
Updated on: 2020-04-02T06:16:54+05:30

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements