[英](MongoDB) Adding a new field to a document with value as the sum of its nested sub-document array
I have following user collection document:我有以下用户收集文件:
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
}
]
}
Now, I am trying to add a new field named schoolAmount
to the top level document by summing amount in the subdocument that is of SCHOOL
type.现在,我正在尝试通过对SCHOOL
类型的子文档中的金额求和来将名为schoolAmount
的新字段添加到顶级文档。 So in the above example document would have schoolAmount: 10.00 // (1 + 9)
.所以在上面的示例文档中会有schoolAmount: 10.00 // (1 + 9)
。 How could I make such a query?我怎么能做这样的查询? I am only aware of simple query like below using the shell.我只知道使用 shell 的简单查询如下所示。
db.user.updateMany({}, {$set: {"schoolAmount": <I need help here>}});
I assumed the document to look like what is inside of user.我假设文档看起来像用户内部的内容。 Then first doing aggregation and storing the output in cursor, then iterating over the cursor I can update the total.然后首先进行聚合并将 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}})
}
Final doc最终文件
{
"_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.