在 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"
      }
   ]
}

更新於:2020 年 4 月 2 日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成該課程獲得認證

開始行動
廣告
© . All rights reserved.