Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In my mongoDB dbs there is a collection A1 that has an array of embedded objects B. I want to group all elements in A1 by the sum of a certain field of B in the array field of A1,namely X. Meanwhile the value of X field need to be an element in another collection A2. That's to say I need to sum up the elements in B array with the X field matching the elements in A2 collection for grouping A1 rather than sum up all elements in B array. I have wrote a query but don't know if it's correct. If not, how to modify it to the right one?
db.A1.aggregate([{$match:{B.X: {$in:A2}}},
                 {$group:{_id:"$ID",Sum: { $sum:"$B.X"}}},
                 {$sort:{Sum: 1}}
                ])
Posted
Updated 29-Sep-15 20:00pm
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900