如何在 MongoDB 中进行聚合后更新?
要更新文档,不能使用聚合管道。您可以使用 update()。让我们首先使用文档创建一个集合 -
> db.demo376.insertOne(
... {
...
... "id" :101,
...
... "details" : [
... {
... Name:"Chris",
... Age:21,
... Score:45
... },
... {
... Name:"David",
... Age:23,
... Score:67
... },
... {
... Name:"Bob",
... Age:20,
... Score:54
... }
... ]
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5a71b92ae06a1609a00b0d")
}使用 find() 方法从集合中显示所有文档 -
> db.demo376.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5e5a71b92ae06a1609a00b0d"),
"id" : 101,
"details" : [
{
"Name" : "Chris",
"Age" : 21,
"Score" : 45
},
{
"Name" : "David",
"Age" : 23,
"Score" : 67
},
{
"Name" : "Bob",
"Age" : 20,
"Score" : 54
}
]
}以下是更新查询 -
> db.demo376.update(
... {"id" :101},
... {$inc:{"details.$[d].Age":3}},
... {arrayFilters: [ {$and:[{"d.Age": 21},{"d.Score": {"$gt":40}} ]}] }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })使用 find() 方法从集合中显示所有文档 -
> db.demo376.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5e5a71b92ae06a1609a00b0d"),
"id" : 101,
"details" : [
{
"Name" : "Chris",
"Age" : 24,
"Score" : 45
},
{
"Name" : "David",
"Age" : 23,
"Score" : 67
},
{
"Name" : "Bob",
"Age" : 20,
"Score" : 54
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP