简体   繁体   English

mongodb中多个集合的总和

[英]Sum from multiple collections in mongodb

I have two collections ie col1 and col2 . 我有两个集合,即col1和col2。
col1 has fields like: col1的字段如下:
_id _ID
user 用户
payout 支付
Col2 reads like Col2读起来像
_id _ID
user 用户
amount

I want output to be sum of payout (from col1) and amount (from col2) 我希望输出是支出(来自col1)和金额(来自col2)的总和

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. 那么您将获得一个“ sumForUser”对象,其中包含每个用户想要的总和。 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. 这也可以通过许多不同的方式来完成,包括使用reduce函数和其他mongoDB函数,例如MapReduce等。 maybe this can be of help. 也许会有所帮助。 also this and this . 还有这个这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM