【问题标题】:Mongodb sum all the same fields in array foreach document - Map-ReduceMongodb对数组foreach文档中的所有相同字段求和 - Map-Reduce
【发布时间】:2015-05-17 23:09:11
【问题描述】:

我的数据库中有这样的文件:

{
"first_name": "John",
"last_name": "Bolt",
"account": [
  {
    "cardnumber": "4844615935257045",
    "cardtype": "jcb",
    "currency": "CZK",
    "balance": 4924.99
  },
  {
    "cardnumber": "3552058835710041",
    "cardtype": "jcb",
    "currency": "BRL",
    "balance": 9630.38
  },
  {
    "cardnumber": "5108757163721629",
    "cardtype": "visa-electron",
    "currency": "CNY",
    "balance": 6574.18
  }
}

我的问题是 - 我怎样才能分别为每个人的所有账户合计余额?我应该使用这个 Map-Reduce 还是聚合框架?

【问题讨论】:

    标签: javascript arrays mongodb mapreduce


    【解决方案1】:

    使用聚合框架。

    这将为您提供一个具有两个属性的对象数组,idbalance 其中id 包含用户名。

    db.document.aggregate([{
      $unwind: "$account"
    }, {
      $group: {
        _id: {$concat: [ "$first_name", " ", "$last_name" ]},
        "balance": {
          $sum: "$account.balance"
        }
      }
    }]);
    

    免责声明:未经测试。

    Ps:我当然希望这是虚拟信息。 Here's another answer 这可能会有所帮助。

    【讨论】:

    • 感谢您的回复,但我想获取所有已分离人员的列表,其中包含每个人的所有余额之和 - 而不是所有人的总余额之和。
    • 哦,不,查询为您提供了专门针对 John Bolt 的所有余额的总和。在这里,我更新了答案中的查询。
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多