我如何 return 一系列捐赠中每个独特捐赠类别的总数?

How can I return the total of each unique donation category from an array of donations?

我有一组礼物对象,其中包括日期、捐赠者捐赠的基金名称和捐赠金额。我想合计每个基金和 return 一个对象捐赠最多的基金以及捐赠给该基金的总额,如果有平局,我想 return两个都。

 donations = [
 {
      donateTo: "BaseCamp",
      amount: 1000,
      date: "12/19/2014, 08:40"
 },
 {
      donateTo: "Where Most Needed",
      amount: 3000,
      date: "12/12/2014, 08:40"
 },
 {
      donateTo: "Where Most Needed",
      amount: 2000,
      date: "12/11/2014, 08:40"
 }
 ];

所以如果我运行上面提到的方法针对这个数组它应该return

{ donateTo: "Where Most Needed", total: 5000, count: 2}

此外,我正在使用 MongoDB 来存储这些值,所以如果有办法在 Mongo 中聚合这些值,那就太好了。

我正在将 MongoDB 与 Meteor 一起使用,所以如果有办法使用 #each 或 #with 来实现这一点,我也很乐意这样做,我只是不确定我是否需要专门的 javascript 函数。

我认为您想使用 MongoDB 中的 grouping 功能来聚合这些值。也请查看该页面上的示例。

试试这个:

db.donations.aggregate([
{$group : {  _id: '$donateTo', total : {$sum : "$amount"}, count: { $sum: 1 }}},
{$sort: {total: -1}},
{$project : { '_id' : 0, 'donateTo' : '$_id', 'total' : '$total', 'count' : '$count'}},
{$limit: 1} ]).result[0]