如何在Mongo聚合查询中合并结果

时间:2020-06-27 18:58:59

标签: mongodb aggregation-framework

我是Mongo中聚合查询的新手,在尝试生成所需的输出时确实很费劲。我有以下聚合查询:

db.events.aggregate([
  { $match: { requestState: "APPROVED" } },
  { $unwind: { path: "$payload.description" } },
  { $group: { _id: { instr: "$payload.description", bu: "$createdByUser", count: { $sum: 1 } } } }
]);

返回以下结果:

{ "_id" : { "instr" : "ABC-123", "bu" : "BU2", "count" : 1 } }
{ "_id" : { "instr" : "ABC-123", "bu" : "BU1", "count" : 1 } }
{ "_id" : { "instr" : "DEF-456", "bu" : "BU1", "count" : 1 } }

如何修改聚合查询,以便仅返回2个文档而不是3个?将两个“ ABC-123”结果合并到一个结果中,并在“ bu”和“ count”字段中添加新的计数数组,即

{ "_id" : { "instr" : "ABC-123", "counts": [ { "bu" : "BU1", "count" : 1 }, { "bu" : "BU2", "count" : 1 } ] } }

非常感谢

1 个答案:

答案 0 :(得分:1)

您可以通过$group仅向_id.instr添加另一个阶段,并向$project添加另一个阶段以达到所需的输出形状

db.events.aggregate([
  {
    $match: { requestState: "APPROVED" }
  },
  {
    $unwind: { path: "$payload.description" }
  },
  {
    $group: {
      _id: { instr: "$payload.description", bu: "$createdByUser", count: { $sum: 1 } }
    }
  },
  {
    $group: {
      _id: { instr: "$_id.instr" },
      counts: { $push: { bu: "$_id.bu", count: "$_id.count" } }
    }
  },
  {
    $project: {
      _id: { instr: "$_id.instr", counts: "$counts" }
    }
  }
]);