Update a single list item of a Mongo DB document and increment it by 1

MongoDBDatabaseBig Data Analytics

For this, use positional operator($). To increment a field value by 1, use $inc operator. Let us create a collection with documents −

>db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-1","ProductPrice":349}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176d54cfb11e5c34d898df")
}
>db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-2","ProductPrice":998}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176d61cfb11e5c34d898e0")
}
>db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-3","ProductPrice":145}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176d6acfb11e5c34d898e1")
}

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

> db.demo39.find();

This will produce the following output −

{ "_id" : ObjectId("5e176d54cfb11e5c34d898df"), "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 349 } ] }
{ "_id" : ObjectId("5e176d61cfb11e5c34d898e0"), "ProductDetails" : [ { "ProductName" : "Product-2", "ProductPrice" : 998 } ] }
{ "_id" : ObjectId("5e176d6acfb11e5c34d898e1"), "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 145 } ] }

Following is the query to update a single list item of a MongoDB document −

> db.demo39.update({"_id" : ObjectId("5e176d61cfb11e5c34d898e0"),'ProductDetails.ProductName':"Product-2"},{$inc: {'ProductDetails.$.ProductPrice': 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo39.find();

This will produce the following output −

{ "_id" : ObjectId("5e176d54cfb11e5c34d898df"), "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 349 } ] }
{ "_id" : ObjectId("5e176d61cfb11e5c34d898e0"), "ProductDetails" : [ { "ProductName" : "Product-2", "ProductPrice" : 999 } ] }
{ "_id" : ObjectId("5e176d6acfb11e5c34d898e1"), "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 145 } ] }
raja
Published on 02-Apr-2020 16:21:45
Advertisements