【问题标题】:How to get aggregation of child collection in mongodb如何在mongodb中获取子集合的聚合
【发布时间】:2017-02-12 12:10:53
【问题描述】:

我有这样的数据结构:

{
  "_id": "order1",
  "transactions": [
    {
      "amount": 100,
      "type": "payment"
    },
    {
      "amount": -10,
      "type": "refund"
    }
  ]
}

我想得到 100+(-10) = 90 的总和。我是 mongodb 的新手。谁能帮我写查询。

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework mongodb-aggregation


    【解决方案1】:
    > db.aaa.aggregate([{$unwind:"$transactions"},{$group:{_id:null, total:{$sum:"$transactions.amount"}}}])
    { "_id" : null, "total" : 90 }
    

    【讨论】:

      【解决方案2】:

      您可以将聚合与 $unwind 一起使用

      .aggregate([
      {$unwind:"$transactions"},
      {$group: {_id:"$_id", total: {$sum: "$transactions.amount"}}}
      ])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 2015-12-06
        • 2020-01-31
        • 2023-03-31
        • 2019-12-29
        相关资源
        最近更新 更多