[英]Adding value to array in sub-document (nested within main doc) without duplication - MongoDB
[英](MongoDB) Adding a new field to a document with value as the sum of its nested sub-document array
我有以下用户收集文件:
user: {
_id: ObjectId("...")
name: "Kid",
items: [
{
name: "pencil",
type: "SCHOOL",
amount: 1.00
},
{
name: "computer",
type: "PERSONAL",
amount: 9999.99
},
{
name: "notebook",
type: "SCHOOL",
amount: 9.00
}
]
}
现在,我正在尝试通过对SCHOOL
类型的子文档中的金额求和来将名为schoolAmount
的新字段添加到顶级文档。 所以在上面的示例文档中会有schoolAmount: 10.00 // (1 + 9)
。 我怎么能做这样的查询? 我只知道使用 shell 的简单查询如下所示。
db.user.updateMany({}, {$set: {"schoolAmount": <I need help here>}});
我假设文档看起来像用户内部的内容。 然后首先进行聚合并将 output 存储在 cursor 中,然后迭代 cursor 我可以更新总数。
var output = db.test.aggregate([{"$match":{name:"Kid"}},{"$unwind":"$items"},{"$match":{"items.type":"SCHOOL"}},{"$group":{"_id":"$name","total" :{$sum: "$items.amount"}}}])
while (output.hasNext()) {
var doc = output.next();
print(doc._id);
print(doc.total);
db.test.update({"name":doc._id},{$set:{"total":doc.total}})
}
最终文件
{
"_id" : ObjectId("5f07e1616fddd269188c731c"),
"name" : "Kid",
"items" : [
{
"name" : "pencil",
"type" : "SCHOOL",
"amount" : 1
},
{
"name" : "computer",
"type" : "PERSONAL",
"amount" : 9999.99
},
{
"name" : "notebook",
"type" : "SCHOOL",
"amount" : 9
}
],
"total" : 10
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.