更新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"
}
]
}热门推荐
6 祝福语简短七夕
10 公司年终晚会祝福语简短
11 给导师送花祝福语简短
12 七姐妹新春祝福语简短
13 宝宝祝福语诗意简短 古文
14 幸福卡片祝福语英文简短
15 父亲简短结婚祝福语大全
16 新娘对伴娘祝福语简短
17 简短正能量生日祝福语
18 对别人新年祝福语简短