Reputation: 5826
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 haveschoolAmount: 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>}});
Upvotes: 2
Views: 59
Reputation: 176
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
}
Upvotes: 1