首先让我们创建一个包含文档的集合-
>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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.decrementingOperationDemo.find().pretty();
这将产生以下输出-
{ "_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 }
以下是查询递减单个值-
> db.decrementingOperationDemo.update({_id: ObjectId("5cd7a8d06d78f205348bc63f"), ProductPrice: {$gt: 0}}, {$inc: {ProductPrice: -10}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档-
> db.decrementingOperationDemo.find().pretty();
这将产生以下输出-
{ "_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 }