Multiple atomic updates using MongoDB?

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 14-May-2020 09:31:09
Advertisements