在 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