Fundamentals of Data Transformation / Using $sort and $limit Stages

Using $sort and $limit Stages

Below is a sample document from a reviews collection and an aggregation pipeline. The pipeline uses the $match, $group, $sort and $limit stages on the reviews collection to identify which books have the highest average ratings based on reviews from 2017 to present.

Code

Sample document from the reviews collection

{    
   _id: ObjectId('67bde3d8776fd7c1b5fce15b'),   
   book_id: ObjectId('67bde3d8776fd7c1b5fce093'),    
   customer_id: ObjectId('67bde3d8776fd7c1b5fce094'),   
   title: 'The Last Stand',   
   rating: 2,    
   review: "I found the book to be boring and unoriginal. It didn't live up to the hype.",    
   timestamp: ISODate('2019-02-23T23:57:22.150Z')
}

Aggregation Pipeline

The output of this aggregation pipeline tells us which books have the highest average ratings based on reviews from 2017 to today.

The $match stage filters for reviews created after 2017.

The $group stage groups documents by the book_id and calculates the average rating for each book using the $avg operator.

The $sort stage sorts these documents in order from highest to lowest value of the averageReview field.

The $limit stage limits the number of output documents to 10 so we only see the top 10 books by customer rating.

db.reviews.aggregate([
    {
        $match: {
            timestamp: {
                $gt: ISODate('2018-01-01T05:00:00.000Z')
            }
        }
    },
    {
        $group: {
            _id: '$book_id',
            averageRating: { $avg: '$rating' }
        }
    },
    { $sort: { averageRating: -1 } },
    { $limit: 10 }
]);

Adding $out to the Aggregation Pipeline

To write the results of the aggregation pipeline to a collection, we can add the $out stage to the end of the pipeline. $out must be the final stage.

In this example, the $out stage will write the results of our pipeline to a collection in the same database called reviews_analysis. If this collection doesn’t exist, then the $out stage will create a new collection. If the specified collection does exist, then all data in the collection will be dropped and replaced with the output of the aggregation pipeline.

db.reviews.aggregate([
    {
        $match: {
            timestamp: {
                $gt: ISODate('2018-01-01T05:00:00.000Z')
            }
        }
    },
    {
        $group: {
            _id: '$book_id',
            averageRating: { $avg: '$rating' }
        }
    },
    { $sort: { averageRating: -1 } },
    { $limit: 10 },
    { $out: 'reviews_analysis' }
]);