Decrement only a single value in MongoDB?



Let us first create a collection with documents −

>db.decrementingOperationDemo.insertOne({"ProductName":"Product-1","ProductPrice":756}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cd7a8ae6d78f205348bc63c") } >db.decrementingOperationDemo.insertOne({"ProductName":"Product-2","ProductPrice":890}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cd7a8b86d78f205348bc63d") } >db.decrementingOperationDemo.insertOne({"ProductName":"Product-3","ProductPrice":994}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cd7a8c66d78f205348bc63e") } >db.decrementingOperationDemo.insertOne({"ProductName":"Product-4","ProductPrice":1000}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cd7a8d06d78f205348bc63f") }

Following is the query to display all documents from a collection with the help of find() method −

> db.decrementingOperationDemo.find().pretty();

This will produce the following output −

{    "_id" : ObjectId("5cd7a8ae6d78f205348bc63c"),    "ProductName" : "Product-1",    "ProductPrice" : 756 } {    "_id" : ObjectId("5cd7a8b86d78f205348bc63d"),    "ProductName" : "Product-2",    "ProductPrice" : 890 } {    "_id" : ObjectId("5cd7a8c66d78f205348bc63e"),    "ProductName" : "Product-3",    "ProductPrice" : 994 } {    "_id" : ObjectId("5cd7a8d06d78f205348bc63f"),    "ProductName" : "Product-4",    "ProductPrice" : 1000 }

Following is the query decrement a single value −

> db.decrementingOperationDemo.update({_id: ObjectId("5cd7a8d06d78f205348bc63f"), ProductPrice: {$gt: 0}}, {$inc: {ProductPrice: -10}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

> db.decrementingOperationDemo.find().pretty();

This will produce the following output −

{    "_id" : ObjectId("5cd7a8ae6d78f205348bc63c"),    "ProductName" : "Product-1",    "ProductPrice" : 756 } {    "_id" : ObjectId("5cd7a8b86d78f205348bc63d"),    "ProductName" : "Product-2",    "ProductPrice" : 890 } {    "_id" : ObjectId("5cd7a8c66d78f205348bc63e"),    "ProductName" : "Product-3",    "ProductPrice" : 994 } {    "_id" : ObjectId("5cd7a8d06d78f205348bc63f"),    "ProductName" : "Product-4",    "ProductPrice" : 990 }
Updated on: 2019-07-30T22:30:26+05:30

831 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements