mongodb - Mongo group inside $addToSet -
i have following set of objects:
[ { id: 1, clientid: 1, cost: 200 }, { id: 1, clientid: 2, cost: 500 }, { id: 1, clientid: 2, cost: 800 }, { id: 2, clientid: 1, cost: 600 }, { id: 2, clientid: 2, cost: 100 } ]
and made group of with:
db.collection.aggregate( { '$group': { '_id': '$id', 'clients': { '$addtoset': { 'id': '$clientid', 'cost': '$cost' } } } } )
so obteined following:
[ { '_id': 1, 'clients': [ { id: 1, cost: 200 }, { id: 2, cost: 500 }, { id: 2, cost: 800 } ], '_id': 2, 'clients': [ { id: 1, cost: 600 }, { id: 2, cost: 100 } ] } ]
as can see in array of clients of first value, have 2 repeated , want have 1 cost added. instead of have:
'clients': [ { id: 1, cost: 200 }, { id: 2, cost: 500 }, { id: 2, cost: 800 } ]
i need:
'clients': [ { id: 1, cost: 200 }, { id: 2, cost: 1300 } ]
so question is: how can that? because $addtoset nor $push allow $sum.
you can use aggregation operators expected output following:
db.collection.aggregate({ "$group": { "_id": { "mainid": "$id", "client": "$clientid" }, "cost": { "$sum": "$cost" } } }, { "$project": { "mainid": "$_id.mainid", "clients": { "clientid": "$_id.client", "cost": "$cost" }, "_id": 0 } }, { "$group": { "_id": "$mainid", "clients": { "$push": "$clients" } } })
Comments
Post a Comment