How to include existing fields in mongodb $ project aggregation operation

I have a sample articles collection that 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 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

 /* 0 */ { "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?

+6
source share
1 answer

You can modify the aggregate pipeline as shown below:

  • Include $ sort to $ group to get entries in ascending order.

  • Then get $ first and $ last for the group that will contain the lowest and highest pages lowest , respectively, for each author.

$$ ROOT is a system variable that is used to refer to the top-level element of the currently processed document.

Modified Code:

 db.articles.aggregate([ {$sort:{"page_views":1}}, {$group:{"_id":"$author", "max":{$last:"$$ROOT"}, "min":{$first:"$$ROOT"}}}, {$project:{"max.page_views":1, "max._id":1, "min.page_views":1, "min._id":1}} ]) 

sample o / p:

 { "_id" : "Bob", "max" : { "_id" : "post 2", "page_views" : 9 }, "min" : { "_id" : "post 1", "page_views" : 5 } } 
+5
source

Source: https://habr.com/ru/post/984585/


All Articles