更新 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 } ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP