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
How to update all documents in MongoDB?
You can use updateMany() to update documents. Let us create a collection with a document. The query to create a collection with a document is as follows −
> db.updateManyDocumentsDemo.insertOne({"StudentName":"John","StudentLastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c948edd4cf1f7a64fa4df48")
}
> db.updateManyDocumentsDemo.insertOne({"StudentName":"John","StudentLastName":"Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c948ee64cf1f7a64fa4df49")
}
> db.updateManyDocumentsDemo.insertOne({"StudentName":"Carol","StudentLastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c948ef14cf1f7a64fa4df4a")
}
> db.updateManyDocumentsDemo.insertOne({"StudentName":"David","StudentLastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c948f044cf1f7a64fa4df4b")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.updateManyDocumentsDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c948edd4cf1f7a64fa4df48"),
"StudentName" : "John",
"StudentLastName" : "Smith"
}
{
"_id" : ObjectId("5c948ee64cf1f7a64fa4df49"),
"StudentName" : "John",
"StudentLastName" : "Doe"
}
{
"_id" : ObjectId("5c948ef14cf1f7a64fa4df4a"),
"StudentName" : "Carol",
"StudentLastName" : "Taylor"
}
{
"_id" : ObjectId("5c948f044cf1f7a64fa4df4b"),
"StudentName" : "David",
"StudentLastName" : "Miller"
}
Here is the query to update all documents. The “StudentName” is updated with “StudentFirstName” −
> db.updateManyDocumentsDemo.updateMany({}, {$rename: {'StudentName': "StudentFirstName"}});
The following is the output −
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }
Check the document has been updated or not. The query is as follows −
> db.updateManyDocumentsDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c948edd4cf1f7a64fa4df48"),
"StudentLastName" : "Smith",
"StudentFirstName" : "John"
}
{
"_id" : ObjectId("5c948ee64cf1f7a64fa4df49"),
"StudentLastName" : "Doe",
"StudentFirstName" : "John"
}
{
"_id" : ObjectId("5c948ef14cf1f7a64fa4df4a"),
"StudentLastName" : "Taylor",
"StudentFirstName" : "Carol"
}
{
"_id" : ObjectId("5c948f044cf1f7a64fa4df4b"),
"StudentLastName" : "Miller",
"StudentFirstName" : "David"
}Advertisements