Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }Advertisements