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
MongoDB query to update all documents matching specific IDs
Use the updateMany() function to update all documents that match the filter criteria. Let us create a collection with documents −
> db.demo476.insertOne({_id:1,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo476.insertOne({_id:2,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo476.insertOne({_id:3,"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo476.insertOne({_id:4,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo476.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Chris" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Bob" }
{ "_id" : 4, "Name" : "Carol" }
Following is the query to update all documents matching specific IDs −
> db.demo476.updateMany({_id:{$in:[1,3]}},{$set:{Name:"Robert"}});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Display all documents from a collection with the help of find() method −
> db.demo476.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Robert" }
{ "_id" : 2, "Name" : "David" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 4, "Name" : "Carol" }Advertisements