汇总期间从一个创建多个文档

时间:2020-10-04 08:32:39

标签: mongodb

我有一个包含以下文档的集合:

{
    "_id" : ObjectId("5f797a8f03b66b73edd4f56f"),
    "totalCounts" : 2300,
    "roadId" : "road_2",
    "type" : "CALL",
    "date" : ISODate("2020-01-11T00:00:00.000Z"),
    "counts" : {
        "GOOD" : 0.652173913043478,
        "BAD" : 0.347826086956522
    }
}

我想进行汇总,以从上述每一项创建两个单独的文档(基于相应的GOOD和BAD计数)。是可能的还是聚合不是我需要使用的?

我需要从每个输入文档中生成如下内容:

{
    "totalCounts" : 2300,
    "roadId" : "road_2",
    "type" : "CALL",
    "date" : ISODate("2020-01-11T00:00:00.000Z"),
    "state": "GOOD",
    "rank": 0.652173913043478
}

{
    "totalCounts" : 2300,
    "roadId" : "road_2",
    "type" : "CALL",
    "date" : ISODate("2020-01-11T00:00:00.000Z"),
    "state": "BAD",
    "rank": 0.347826086956522
}

1 个答案:

答案 0 :(得分:2)

您可以喜欢以下内容

[
  {
    $set: {
      counts: {
        $objectToArray: "$counts"
      }
    }
  },
  {
    $unwind: "$counts"
  },
  {
    $set: {
      state: "$counts.k",
      rank: "$counts.v"
    }
  },
  {
    $project: {
      counts: 0
    }
  }
]

工作Mongo playground