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
Multiple atomic updates using MongoDB?
For multiple atomic updates, use update() along with $set. Let us create a collection with documents −
> db.demo699.insertOne({Name:"Chris Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6e370551299a9f98c93a7")
}
> db.demo699.insertOne({Name:"David Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6e37a551299a9f98c93a8")
}
> db.demo699.insertOne({Name:"Chris Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6e381551299a9f98c93a9")
}
> db.demo699.insertOne({Name:"John Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6e38a551299a9f98c93aa")
}
Display all documents from a collection with the help of find() method −
> db.demo699.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6e370551299a9f98c93a7"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5ea6e37a551299a9f98c93a8"), "Name" : "David Miller" }
{ "_id" : ObjectId("5ea6e381551299a9f98c93a9"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5ea6e38a551299a9f98c93aa"), "Name" : "John Doe" }
Following is the query to perform multiple atomic updates using MongoDB −
> db.demo699.update({Name:"Chris Brown"},{ $set : { Name: "Adam Smith"} }, false, true );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Display all documents from a collection with the help of find() method −
> db.demo699.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6e370551299a9f98c93a7"), "Name" : "Adam Smith" }
{ "_id" : ObjectId("5ea6e37a551299a9f98c93a8"), "Name" : "David Miller" }
{ "_id" : ObjectId("5ea6e381551299a9f98c93a9"), "Name" : "Adam Smith" }
{ "_id" : ObjectId("5ea6e38a551299a9f98c93aa"), "Name" : "John Doe" }Advertisements