MongoDB 将组对象转换为 key:value (_id:count) 对象

MongoDB convert group object to key:value (_id:count) object

我有一个结果类似的聚合管道。

[
   {
      "_id":"1621",
      "count":567
   },
   {
      "_id":"1658",
      "count":1089
   }
   ...
]

如何将此结果转换为 key:value 对 ("_idValue": "countValue"),就像这样?

   {
      "1621": 567,
      "1658": 1089
      ...
   }

我的管道是:

pipeline = [
    {'$match': {
        'date': {'$gte': start_date, '$lt': end_date}
    }},
    {
        '$group': {
            '_id': '$networkId',
            'count': {'$sum': 1}
        }
    },
    {
        '$sort': {'_id': 1}
    },

]

在管道阶段之后添加以下阶段,

  • $group由null构成键值对数组
  • $arrayToObject 将上述格式化数组转换为对象
  • $repalceRoot 将上面转换后的对象替换为 root
pipeline = [
  // .. add your pipeline stages here
  {
    $group: {
      _id: null,
      object: {
        $push: { k: "$_id", v: "$count" }
      }
    }
  },
  {
    $replaceRoot: { newRoot: { $arrayToObject: "$object" } }
  }
]

Playground