Syntax error What is the fastest way to update the whole document (all fields) in MongoDB?

What is the fastest way to update the whole document (all fields) in MongoDB?



The fastest way is to use replaceOne() in MongoDB. Let us create a collection with documents −

> db.demo431.insertOne({"Name":"Chris","Age":32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e770ba6bbc41e36cc3cae89")
}
> db.demo431.insertOne({"Name":"David","Age":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e770bacbbc41e36cc3cae8a")
}
> db.demo431.insertOne({"Name":"John","Age":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e770bb3bbc41e36cc3cae8b")
}
> db.demo431.insertOne({"Name":"Bob","Age":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e770bb8bbc41e36cc3cae8c")
}

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

> db.demo431.find();

This will produce the following output −

{ "_id" : ObjectId("5e770ba6bbc41e36cc3cae89"), "Name" : "Chris", "Age" : 32 }
{ "_id" : ObjectId("5e770bacbbc41e36cc3cae8a"), "Name" : "David", "Age" : 31 }
{ "_id" : ObjectId("5e770bb3bbc41e36cc3cae8b"), "Name" : "John", "Age" : 24 }
{ "_id" : ObjectId("5e770bb8bbc41e36cc3cae8c"), "Name" : "Bob", "Age" : 22 }

Following is the query to update the whole document (all fields) in MongoDB −

> db.demo431.replaceOne(
...    { "Name" : "John" },
...    { "Name" : "Robert", "Age" :45 }
... );
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

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

> db.demo431.find();

This will produce the following output −

{ "_id" : ObjectId("5e770ba6bbc41e36cc3cae89"), "Name" : "Chris", "Age" : 32 }
{ "_id" : ObjectId("5e770bacbbc41e36cc3cae8a"), "Name" : "David", "Age" : 31 }
{ "_id" : ObjectId("5e770bb3bbc41e36cc3cae8b"), "Name" : "Robert", "Age" : 45 }
{ "_id" : ObjectId("5e770bb8bbc41e36cc3cae8c"), "Name" : "Bob", "Age" : 22 }
Updated on: 2020-04-03T14:10:34+05:30

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements