更新 MongoDB 文档的单个列表项并将其增量 1


为此,请使用位置运算符($)。要将字段值增量 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 } ] }

更新于: 02-Apr-2020

66 次浏览

开启你的 职业

完成课程,获得认证

开始
广告
© . All rights reserved.