用於在陣列中設定子項的 MongoDB 查詢是什麼?
你可以使用位置 $ 運算子。讓我們使用文件建立一個集合:
> db.demo22.insertOne(
... {
... ProductId:101,
...
... ProductDetails:
... [
... {
... ProductFirstPrice: '35',
... ProductSecondPrice: '75'
... },
... {
... ProductFirstPrice: '',
... ProductSecondPrice:''
... },
... {
... ProductFirstPrice: '78',
... ProductSecondPrice:'24'
... }
... ]
... }
...
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e14c0b422d07d3b95082e70")
}使用 find() 方法顯示集合中的所有文件:
> db.demo22.find().pretty();
這將產生以下輸出:
{
"_id" : ObjectId("5e14c0b422d07d3b95082e70"),
"ProductId" : 101,
"ProductDetails" : [
{
"ProductFirstPrice" : "35",
"ProductSecondPrice" : "75"
},
{
"ProductFirstPrice" : "",
"ProductSecondPrice" : ""
},
{
"ProductFirstPrice" : "78",
"ProductSecondPrice" : "24"
}
]
}以下是用於在陣列中設定子項的 MongoDB 查詢:
> db.demo22.update({ "ProductDetails.ProductFirstPrice" : "35" },
... { $set : { "ProductDetails.$.ProductFirstPrice" : "" }}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })使用 find() 方法顯示集合中的所有文件:
> db.demo22.find().pretty();
這將產生以下輸出:
{
"_id" : ObjectId("5e14c0b422d07d3b95082e70"),
"ProductId" : 101,
"ProductDetails" : [
{
"ProductFirstPrice" : "",
"ProductSecondPrice" : "75"
},
{
"ProductFirstPrice" : "",
"ProductSecondPrice" : ""
},
{
"ProductFirstPrice" : "78",
"ProductSecondPrice" : "24"
}
]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP