簡體   English   中英

(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM