在 MongoDB 中更新陣列中的多個元素?
若要更新多個元素,請使用 $[]. $[] 是一個全部位置運算子,表示更新運算子應該修改指定陣列欄位中的所有元素。
讓我們首先使用文件建立集合 −
> db.demo385.insertOne({"ServerLogs": [
... {
... "status":"InActive"
... },
... {
... "status":"InActive"
... },
... {
... "status":"InActive"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5b6a7522064be7ab44e7f5")
}使用 find() 方法從集合顯示所有文件 −
> db.demo385.find().pretty();
這將產生以下輸出 −
{
"_id" : ObjectId("5e5b6a7522064be7ab44e7f5"),
"ServerLogs" : [
{
"status" : "InActive"
},
{
"status" : "InActive"
},
{
"status" : "InActive"
}
]
}以下是更新 MongoDB 中陣列中多個元素的查詢 −
> db.demo385.update(
... { "_id" : ObjectId("5e5b6a7522064be7ab44e7f5") },
... { "$set": { "ServerLogs.$[].status": "Active" }}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })使用 find() 方法從集合顯示所有文件 −
> db.demo385.find().pretty();
這將產生以下輸出 −
{
"_id" : ObjectId("5e5b6a7522064be7ab44e7f5"),
"ServerLogs" : [
{
"status" : "Active"
},
{
"status" : "Active"
},
{
"status" : "Active"
}
]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP