在 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.