Mongo DB - Group status and get total count using aggregation

mongodb aggregation-framework

513 观看

1回复

8 作者的声誉

I had created a collection posts, and added documents which look like this.

[{
    "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"
}]

I need to use aggregation function that will count,
1. Total posts assign to a particular person(here only sukesh), and
2. Total status's count, if status not assign then it will return 0.
like below.

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

please help me to get solution.

作者: Sudhakar Jonnakuti 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

1789 作者的声誉

决定

I don't think this is possible exactly as you want, but you can try if you can use this:

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
  } 
}
])
作者: Alex P. 发布者: 2017 年 12 月 27 日
32x32