在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
}
]
}
以上是 在MongoDB中汇总后如何更新? 的全部内容, 来源链接: utcz.com/z/334856.html