Mongo-汇总-按子键分组结果

时间:2018-08-23 20:35:20

标签: mongodb formatting aggregation-framework aggregate

我有一个包含此对象的集合:

 {
  "asset": {
    "_id": "xyz",
    "measurments": [{
        "name": "Name 1",
        "value": 1,
        "source": "sourceName1",
        "active": true
      }, {
        "name": "Name 2",
        "value": 2,
        "source": "sourceName2",
        "active": true
      },
      {
        "name": "Name 3",
        "value": 3,
        "source": "sourceName1",
        "active": true
      },
      {
        "name": "Name 4",
        "value": 3,
        "source": "sourceName1",
        "active": false
      }
    ]
  }
}

我只需要检索活动的度量并将其按来源分组。 我已经成功构建了聚合查询的第一部分,并且仅检索了活动的测量值

[{ $match: { "_id": "xyz" } },
{
  $project: {
    measurments: {
      $filter: {
        input: "$measurments",
        as: "measurments",
        cond: { $eq: ["$$measurments.active", true] }
      }
    }
  }
}]

但是我很难在小组部分中使结果看起来像这样:

 [{
     "source": "sourceName1",
     "names": ["Name 1", "Name 3"]
 }, {
    "source": "sourceName2",
    "names": ["Name 2"]
 }]

感谢您的帮助。

0 个答案:

没有答案