Skip to content

Instantly share code, notes, and snippets.

@shamsher31
Last active August 29, 2015 14:25
Show Gist options
  • Save shamsher31/a9605219c484323b6477 to your computer and use it in GitHub Desktop.
Save shamsher31/a9605219c484323b6477 to your computer and use it in GitHub Desktop.
Mongodb blog status based on author example
//http://stackoverflow.com/questions/31649223/mongodb-aggregate-blog-post-based-on-status/31649870#31649870
//Also refer this http://stackoverflow.com/questions/12700836/mongodb-aggregate-query-equivalent-to-postsgresql
How to get the output like this
[{
"_id" : ObjectId('dshe1hhdsa12dashe21dqs'),
"blogId" : 'dhsad78sa6dsa66ds6ds6ds8ds',
"published" : 10,
"approved" : 15,
"pending" : 5
},
{
"_id" : ObjectId('dshe1hhdsa12dashe21dqs'),
"blogId" : 'dhsad78sa6dsa66ds6ds6ds8ds',
"published" : 10,
"approved" : 15,
"pending" : 5
}]
Query :
var query = [
{
$match:
{
status: { $in : ['Published', 'Approved', 'Pending']}
}
},
{
$group: {
_id: {
blogId:"$blogId"
},
published: {
$sum:{
$cond:[
{$eq:["$status","Published"]},
1,
0
]
}
},
approved: {
$sum: {
$cond:[
{$eq:["$status","Approved"]},
1,
0
]
}
},
pending: {
$sum: {
$cond:[
{$eq:["$status","Pending"]},
1,
0
]
}
}
}
},
{
$project: {
_id: 0,
blogId: "$_id.blogId",
published: "$published",
approved: "$approved",
pending: "$pending"
}
}
];
db.blog.aggregate(query);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment