Mongo DB - 使用聚合分组状态并获取总计数

时间:2017-12-27 17:37:31

标签: mongodb aggregation-framework

我创建了一个收集帖子,并添加了这样的文档。

[{
    "title" : "MongoDB-Overview", 
    "status" : "created",
    "postBy" : "sukesh"
}, {
    "title" : "MongoDB-Collection", 
    "status" : "created",
    "postBy" : "sukesh"
}, {
    "title" : "MongoDB-Document", 
    "status" : "approved",
    "postBy" : "sukesh"
}, {
    "title" : "MongoDB-Database", 
    "status" : "approved_pending",
    "postBy" : "ramesh"
}, {
    "title" : "MongoDB-Query", 
    "status" : "deleted",
    "postBy" : "suresh"
}]

我需要使用计数的聚合函数,
1.总职位分配给特定的人(这里只有sukesh),和 2.总状态计数,如果状态未分配,则返回0 如下。

{
   "postby": "sukesh"
   "totalPost": 4,
   "status": {
      "created": 2
      "approved": 1,
      "approved_pending": 0,
      "deleted": 1
    }       
}

请帮我解决问题。

1 个答案:

答案 0 :(得分:0)

我认为这不可能完全符合您的要求,但您可以尝试使用它:

db.collection.aggregate([
{
  $group: {
    _id: "$postBy",
    count: { $sum: 1},
    status: { $push: "$status"}
  }
},
{ $unwind: "$status"},
{
  $group: {
    _id: { "postby": "$_id", status: "$status" },
    scount: { $sum: 1},
    count: {$first: "$count"}
  }
}, 
{$group: {
        _id: "$_id.postby",  
        total: {$first: "$count"},
        status: {$push:  { type: "$_id.status", count: "$scount" }},
}},
{
  $project: {
    _id: 0,
    postby: "$_id",
    totalPost: "$total",
    status: 1
  } 
}
])