简体   繁体   中英

(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. So in the above example document would have schoolAmount: 10.00 // (1 + 9) . How could I make such a query? I am only aware of simple query like below using the 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM