更新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"
}
]
}热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短