如何将项目分组到 mongodb 中的对象?

how to project grouping into object in mongodb?

我正在尝试使用此聚合查询在 mongodb 中执行一个简单的 GROUP BY/COUNT:

{
  $match:{
    'os':7
  }
},
{
  $group : {
    _id:"$status", 
    count:{$sum:1}
  }
},
{
  $project:{
    count:1,
    status:1
  }
}

是return这样的数组

[{ "_id" : "ENC", "count" : 18 }
{ "_id" : "INT", "count" : 363 }
{ "_id" : "ANN", "count" : 132 }]

有没有办法使用分组字段作为键将结果投影到对象中? 例如:

{
   ENC:18, 
   INT:363, 
   ANN:132
}

谢谢

我不认为 MongoDB 的聚合框架在结果对象上有 $project operations that can convert field values into keys. You could try convert the aggregation result using the forEach() cursor method to iterate over the projected fields and use JavaScript's bracket-notation 然后创建所需的最终对象:

var result = [
    { "_id" : "ENC", "count" : 18 },
    { "_id" : "INT", "count" : 363 },
    { "_id" : "ANN", "count" : 132 }
];
var obj = {};
result.forEach(function (doc){
    obj[doc._id] = doc.count;
});
printjson(obj); // {ENC: 18, INT: 363, ANN: 132}