How to do conditional update in MongoDB?

MongoDBDatabaseBig Data Analytics

Use update() for conditional update in MongoDB. Let us first create a collection with documents −

> db.demo402.insertOne({id:101,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e61214efac4d418a0178585")
}
> db.demo402.insertOne({id:102,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e612150fac4d418a0178586")
}
> db.demo402.insertOne({id:103,"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e612152fac4d418a0178587")
}

Display all documents from a collection with the help of find() method −

> db.demo402.find();

This will produce the following output −

{ "_id" : ObjectId("5e61214efac4d418a0178585"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e612150fac4d418a0178586"), "id" : 102, "Name" : "David" }
{ "_id" : ObjectId("5e612152fac4d418a0178587"), "id" : 103, "Name" : "Mike" }

Following is the query to perform conditional update in MongoDB −

> db.demo402.update({id:102},
... {
...    $set: { Name: "Robert" }
... },
... {upsert: true }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo402.find();

This will produce the following output −

{ "_id" : ObjectId("5e61214efac4d418a0178585"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e612150fac4d418a0178586"), "id" : 102, "Name" : "Robert" }
{ "_id" : ObjectId("5e612152fac4d418a0178587"), "id" : 103, "Name" : "Mike" }
raja
Published on 03-Apr-2020 12:43:45
Advertisements