【问题标题】:MongoDB nested groups aggregationMongoDB 嵌套组聚合
【发布时间】:2020-10-30 09:38:38
【问题描述】:

我在 mongodb 中有一组数据,如下所示:

{_id: ObjectId(""), created: date, otherObjectId: ObjectId(""), amount: number}

是否可以按年、按月、然后按 otherCollectionID 编写聚合?像这样的:

[{year: [{month: [{otherCollectionID: {amount: "$amount"}}]}

我可以按年和月汇总,但我不确定如何为第二个对象 ID 字段添加另一个组。

db.Collection.aggregate([
    {$match: {status: 'succeeded'}},
    {
      $group: {
        _id: {
          year: {"$year": '$created'},
          month: {"$month": '$created'},
          otherObjectId: "$otherObjectId"
        },
        count: {$sum: 1},
        amount: {$sum: '$amount'}
      }
    }, 
    {
      $group: {
        _id: "$_id.year",
        "data": {
          $push: {
            month: "$month",
            count: "$count",
            amount: "$amount"
          }
        }
      }
    }
  ])

这样的结果是:

{
    "_id" : 2020,
    "data" : [
        {
            "count" : 4,
            "amount" : 200
        },
        {
            "count" : 1,
            "amount" : 50
        },
    ... for other months
  ]
}

【问题讨论】:

  • 您能添加您的预期结果吗?

标签: javascript node.js mongodb mongodb-query aggregation-framework


【解决方案1】:

在进一步阅读 mongo 文档后,我实际上得到了它。这是我的查询:

db.Collection.aggregate([
    { $lookup: {
       from: "OtherCollection",
       localField: "otherObjectId",
       foreignField: "_id",
       as: "otherData"
    }},
    { $unwind: "$otherData" },
    { $project: {
      "_id": 1,
      "created": 1,
      "amount": 1,
      "otherObjectId": 1,
      "otherData.field": 1
    }},
    { $group: {
        _id: {
          year: {"$year": '$created'},
          month: {"$month": '$created'},
        },
        otherData: {
          $addToSet: "$otherData"
        },
        count: {$sum: 1},
        amount: {$sum: '$amount'}
      }
    }, 
    { $group: {
        _id: {year: "$_id.year", month: "$_id.month"},
        data: {
          $push: {
            count: "$count",
            amount: "$amount",
            otherData: "$otherData"
          }
        }
      }
    },
    { $sort: {
      "_id.year": 1,
      "_id.month": 1 
    }}
  ])

这将导致:

"_id" : {
        "year" : 2015,
        "month" : 12
    },
    "data" : [
        {
            "count" : 7,
            "amount" : 70,
          "otherData" : []
        }
    ]
}
{
    "_id" : {
        "year" : 2016,
        "month" : 1
    },
    "data" : [
        {
            "count" : 27,
            "amount" : 10000,
            "otherData" : []
        }
    ]
}
...

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 2017-07-26
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2021-04-19
    • 2021-03-13
    • 2021-06-27
    相关资源
    最近更新 更多