为此,请使用位置运算符($)。要将字段值加1,请使用$inc运算符。让我们创建一个包含文档的集合-
>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")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo39.find();
这将产生以下输出-
{ "_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 } ] }以下是更新MongoDB文档的单个列表项的查询-
> db.demo39.update({"_id" : ObjectId("5e176d61cfb11e5c34d898e0"),'ProductDetails.ProductName':"Product-2"},{$inc: {'ProductDetails.$.ProductPrice': 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })在find()方法的帮助下显示集合中的所有文档-
> db.demo39.find();
这将产生以下输出-
{ "_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 } ] }