I have a sample collection articles which contains the following data:
/* 0 */
{
"_id" : "post 1",
"author" : "Bob",
"content" : "...",
"page_views" : 5
}
/* 1 */
{
"_id" : "post 2",
"author" : "Bob",
"content" : "...",
"page_views" : 9
}
/* 2 */
{
"_id" : "post 3",
"author" : "Bob",
"content" : "...",
"page_views" : 8
}
I would like to use the aggregation framework to find the min and max value for page views for a given author, and in the process display the _id of the article with the min/max value. This is my expected output:
{ _id : "Bob",
value : { min : { page_views : 5 , _id : "post 1" } ,
max : { page_views , 9 , _id : "post 3" } } }
I've tried implementing this aggregation pipeline:
db.articles.aggregate([
{
"$group": {
"_id": "$author",
"min_page_views": {
"$min": "$page_views"
},
"max_page_views": {
"$max": "$page_views"
}
}
},
{
"$project": {
"_id": 1,
"min": {
"page_views": "$min_page_views",
"_id": "$_id"
},
"max": {
"page_views": "$max_page_views",
"_id": "$_id"
}
}
}
])
Output:
/* 0 */
{
"result" : [
{
"_id" : "Bob",
"min" : {
"page_views" : 5,
"_id" : "Bob"
},
"max" : {
"page_views" : 9,
"_id" : "Bob"
}
}
],
"ok" : 1
}
I cannot seem to get the other field max._id or min._id which gives the original document id before projection. How do I change my aggregation pipeline so that I can include this field as well?