【问题标题】:How can I return the total of each unique donation category from an array of donations?如何从一系列捐赠中返回每个独特捐赠类别的总数?
【发布时间】:2015-03-10 12:33:01
【问题描述】:

我有一系列礼物对象,其中包括日期、捐赠者捐赠的基金名称和捐赠金额。我想将每个基金的捐赠金额加起来,然后将捐赠最多的基金以及捐赠给该基金的总额归还给一个对象,如果有平局,我想将它们都归还。

 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"
 }
 ];

所以如果我对这个数组运行上述方法,它应该返回

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

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

我将 MongoDB 与 Meteor 一起使用,所以如果有办法使用 #each 或 #with 来获得它,我也很乐意这样做,我只是不确定是否需要 javascript独占与否。

【问题讨论】:

    标签: javascript mongodb meteor mongodb-query aggregation-framework


    【解决方案1】:

    试试这个:

    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]
    

    【讨论】:

    • 我试过了,它似乎不起作用。我得到了{ "total" : 3400, "count" : 1, "donateTo" : "Philippines Infrastructure" } 的输出,我通过手动查看集合确定这不是应该排在首位的。
    • 对于您的示例文档,我有:{ "total" : 5000, "count" : 2, "donateTo" : "Where Most Needed" }
    • 如果我删除这部分 , {$project : { '_id' : 0, 'donateTo' : '$_id', 'total' : '$total', 'count' : '$count'}}, {$limit: 1} ]).result[0] 并再次运行它,我会得到这个数组。 gist.github.com/c316/f642f378713110fca7be
    • 啊,好的,做到了。谢谢
    • 感谢您的帮助和非常快速的答复。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2015-06-30
      • 2011-03-09
      • 2013-03-29
      • 2016-01-04
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多