MongoDB Aggregation Pipeline | MongoDB Atlas | MongoDB Shell

Rank Top 10 Items by Views

Using CRUD Operations & Aggregation pipelines for processing data stored in mongodb documents and collections

Saheel Sapovadia

--

To cut the long story short, I am developing a Novel reading website and want a feature similar to what Netflix has- Today’s Top 10. For that some sort of data processing is required which would run on all the documents of Novels Collection stored in my MongoDB database.

Run Commands in mongosh

For documentation of basic MongoDB operations in mongosh, see:

There are a number of ways you can perform operations and run pipelines and the one which I’ll be using is a VS Code extension. You can get the information from the below link-

The whole process of installing, connecting and exploring all the features is very well documented.

Lets Begin

Our use case requires Sorting all the Novels in descending order by the views field, retrieving the top 10 from the result and storing those in another Collection.

For this we’ll use something called Aggregation Pipelines.

What is aggregation?

Run Aggregation Pipelines

There are Aggregation Pipelines Stages. Documents pass through the stages in sequence. Each stage is responsible for a task of its own.

In our case we’ll use $sort to sort all the Novels, then $limit to limit the number to top 10 only and then $out to write the resulting documents of the pipeline to a collection. These all are called the stages of our pipeline.

My Novel document-

MongoDB Playground file-

This code will result in [] because the output is stored in the ‘topNovels’ collection as specified in the last stage. For testing purposes /in-development stage exclude the $out stage to verify the results in Result Tab. Also, I have set the limit to 2 because currently there aren’t enough novels in the collection 😁😅

MongoDB Playground

This was all you need to do to get your top whatever items in any fashion you want.

Fun Part

In the cloud console of MongoDB Atlas in collections tab you’ll find Aggregation tab, where you can set all the stages and obtain the results.

Mongo Atlas
  1. $sort stage -
sorting

2. $limit stage -

limiting

3. $out stage -

storing results to specific location

Though you can see the ‘Add Stage’ option after the $out stage, but technically the $out stage has to be the last one in the Aggregation Pipeline.

I referred a few documentations and resources to understand and complete the task. Those who are new to this, this article will definitely save you from getting lost and save your precious learning hours.

Thanks for reading this article! Leave a comment below if you have any questions. Make sure to give this post 50 claps and a follow if it really helped you and if you want to see more.

--

--

Saheel Sapovadia

I spend hours on learning new tools, so that you don’t have to. #techSavvyTeen