I have two collections i.e. col1 and col2 .
col1 has fields like:
_id
user
payout
Col2 reads like
_id
user
amount
I want output to be sum of payout (from col1) and amount (from col2)
1 Answers
why not just find the data in both collections and then pass both objects into a function thats adds to the sum? something like this:
var sum = 0;
//do this for both collections
db.collection.find({}).forEach(function(obj){
sum+=obj.payout;
});
if what you wanted to do was get the overall sum forEach different user you could do something like this:
var sumForUser = {};
//do this for both collections
db.collection.find({}).forEach(function(obj){
if ( sumForUser[obj.user] ) {
sumForUser[obj.user] += obj.payout;
else
sumForUser[obj.user] = obj.payout;
});
then you would a "sumForUser" object with the sum you wanted for every user. this you would be a "map" of user to sum.
this could also be done in many different ways, including use of reduce functions and other mongoDB functions such as MapReduce and so on. maybe this can be of help. also this and this.

- 61
- 5
-
Can you please explain further? Each collection has multiple entries by same user – Joe Mutti Sep 09 '18 at 04:14
-
what is your expected output? the sum of amount and payout per user? or the total amount and payout for every one? – K.Daniel Sep 09 '18 at 09:43
-
Sum of all payouts and amounts of a user together – Joe Mutti Sep 09 '18 at 09:46