MongoDB Aggregation with sum of array values -
i have collection following data:
{ "_id" : objectid("5516d416d0c2323619ddbca8"), "date" : "28/02/2015", "driver" : "user1", "passengers" : [ { "user" : "user2", "times" : 2 }, { "user" : "user3", "times" : 3 } ] } { "_id" : objectid("5516d517d0c2323619ddbca9"), "date" : "27/02/2015", "driver" : "user2", "passengers" : [ { "user" : "user1", "times" : 2 }, { "user" : "user3", "times" : 2 } ] }
and perform aggregation know passenger, times driver, in example be: user1: [{ driver: user2, times: 2}]
user2: [{ driver: user1, times: 2}]
user3: [{ driver: user1, times: 3}, {driver: user2, times:2}]
im quite new mongo , know how perform easy aggregation sum, not when inside arrays, , when subject in array. appropriate way perform kind of aggregation, , in more specific, how perform in express.js based server?
to achieve needs aggregation framework, first pipeline stage $match
operation on passenger in question matches documents user in passenger array, followed $unwind
operation deconstructs passengers array input documents in previous operation output document each element. $match
operation on deconstructed array follows further filters previous document stream allow matching documents pass unmodified next pipeline stage, projecting required fields $project
operator. aggregation pipeline user3
like:
db.collection.aggregate([ { "$match": { "passengers.user": "user3" } }, { "$unwind": "$passengers" }, { "$match": { "passengers.user": "user3" } }, { "$project": { "_id": 0, "driver": "$driver", "times": "$passengers.times" } } ])
result:
/* 0 */ { "result" : [ { "driver" : "user1", "times" : 3 }, { "driver" : "user2", "times" : 2 } ], "ok" : 1 }
update:
for grouping duplicates on drivers different dates, mentioned can $group
operation before last $project
pipeline stage compute total passengers times using $sum
operator:
db.collection.aggregate([ { "$match": { "passengers.user": "user3" } }, { "$unwind": "$passengers" }, { "$match": { "passengers.user": "user3" } }, { "$group": { "_id": "$driver", "total": { "$sum": "$passengers.times" } } }, { "$project": { "_id": 0, "driver": "$_id", "total": 1 } } ])
result:
/* 0 */ { "result" : [ { "total" : 2, "driver" : "user2" }, { "total" : 3, "driver" : "user1" } ], "ok" : 1 }
Comments
Post a Comment