I have a sample articles collection that contains the following data:
{ "_id" : "post 1", "author" : "Bob", "content" : "...", "page_views" : 5 } { "_id" : "post 2", "author" : "Bob", "content" : "...", "page_views" : 9 } { "_id" : "post 3", "author" : "Bob", "content" : "...", "page_views" : 8 }
I would like to use the aggregation structure to find the minimum and maximum values ββfor page views for this author, and in the process displays the _id of the article with the value min / max. This is my expected result:
{ _id : "Bob", value : { min : { page_views : 5 , _id : "post 1" } , max : { page_views , 9 , _id : "post 3" } } }
I tried to implement 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
{ "result" : [ { "_id" : "Bob", "min" : { "page_views" : 5, "_id" : "Bob" }, "max" : { "page_views" : 9, "_id" : "Bob" } } ], "ok" : 1 }
I can not get another field max._id or min._id , which gives the original document identifier before the projection. How do I change the aggregation pipeline so that I can include this field?