I have a use case where I need to show top 10 and last 10 results from a group and sorted aggregation. I tried to use $limit but that will not let the next aggregators to work on the complete data.
db.collection.aggregate([groupAggregator, sortAggregator, { $limit: 10 }, /*only 10 records available*/]
How to perform aggregations on the whole collection in the middle of the pipeline? I am using MongoDB 3.2.9. If that's impossible is there a way to UNION two aggregations the first one being the top 10 (ASC SORTED) and the second one last 10 (DESC SORTED),
Had it not been for the group aggregation I would have used the db.collection.find({}).sort().filter() strategy but the group needs to be done.
Data obtained from group aggregation
{_id: "", ..., avg_count: 10}
{_id: "", ..., avg_count: 1}
{_id: "", ..., avg_count: 2}
{_id: "", ..., avg_count: 5}
{_id: "", ..., avg_count: 8}
{_id: "", ..., avg_count: 3}
{_id: "", ..., avg_count: 4}
{_id: "", ..., avg_count: 6}
{_id: "", ..., avg_count: 7}
{_id: "", ..., avg_count: 9}
Data obtained from Sort aggregation
{_id: "", ..., avg_count: 1}
{_id: "", ..., avg_count: 2}
{_id: "", ..., avg_count: 3}
{_id: "", ..., avg_count: 4}
{_id: "", ..., avg_count: 5}
{_id: "", ..., avg_count: 6}
{_id: "", ..., avg_count: 7}
{_id: "", ..., avg_count: 8}
{_id: "", ..., avg_count: 9}
{_id: "", ..., avg_count: 10}
DESIRED OUTPUT:
FETCH FIRST 2 AND LAST 2 documents
{_id: "", ..., avg_count: 1}
{_id: "", ..., avg_count: 2}
{_id: "", ..., avg_count: 9}
{_id: "", ..., avg_count: 10}
NOTE: The above is just a sample data, actual data does not have exact serial numbers.