我有一个聚合管道,结果是这样的。
[
{
"_id":"1621",
"count":567
},
{
"_id":"1658",
"count":1089
}
...
]
我如何将这个结果转换为键:值对("_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
将上述转换后的对象替换为根
pipeline = [
// .. add your pipeline stages here
{
$group: {
_id: null,
object: {
$push: { k: "$_id", v: "$count" }
}
}
},
{
$replaceRoot: { newRoot: { $arrayToObject: "$object" } }
}
]
游乐场