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
}
raja
Published on 13-Jun-2019 12:05:04
Advertisements