Sort Aggregation in MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you plan to perform aggregation operations in MongoDB, it’s important to get acquainted with the stages of the aggregation pipeline. Documents enter the pipeline and pass through various stages. At each stage, some type of transformation occurs, and the transformed results are then passed to the next stage of the pipeline. In this article, we’ll focus our attention on the $sort stage. We’ll explain how to perform a sort aggregation in MongoDB and show you some examples to illustrate the process.

Prerequisite

Before we proceed with our discussion of the sort aggregation in MongoDB, let’s review the two key prerequisites for the task:

  • MongoDB needs to be installed and configured on your system.
  • You should have some basic knowledge of MongoDB.

What is MongoDB $sort

In MongoDB, the $sort stage is used to sort all the documents in the aggregation pipeline and pass a sorted order to the next stage of the pipeline.

The basic form of the $sort stage can be seen below:

1
{ $sort: { <field_1>: <sort order>, <field_2>: <sort order> ... } }

Lets take a closer look at the above syntax:

The $sort stage accepts a document that defines the field or fields that will be used for sorting. In this example, documents will be sorted by ‘field_1’ and ‘field_2’ in the sorting order specified in the argument.

To specify an ascending sort order, we provide the value of ‘1’. For descending order, we use the value of ‘-1’.

Create Sample Data Set

Let’s create a sample collection that we can use for demo purposes in our examples. Here’s the command we’ll use to create the student collection:

1
2
3
4
5
6
7
8
9
db.student.insertMany([
    {_id:1,name: "rommel", age: 21, "email": "rommel@example.com"},
    {_id:2,name: "joseph", age: 24, "email": "joseph@example.com"},
    {_id:3,name: "jokoy", age: 22, "email": "jokoy@example.com"},
    {_id:4,name: "dan", age: 22, "email": "dan@example.com"},
    {_id:5,name: "steve", age: 21, "email": "steve@example.com"},
    {_id:6,name: "james", age: 24, "email": "james@example.com"},
    {_id:7,name: "greg", age: 23, "email": "greg@example.com"}
]);

After executing this command, our collection will look like the following:

1
2
3
4
5
6
7
{ "_id" : 1, "name" : "rommel", "age" : 21, "email" : "rommel@example.com" }
{ "_id" : 2, "name" : "joseph", "age" : 24, "email" : "joseph@example.com" }
{ "_id" : 3, "name" : "jokoy", "age" : 22, "email" : "jokoy@example.com" }
{ "_id" : 4, "name" : "dan", "age" : 22, "email" : "dan@example.com" }
{ "_id" : 5, "name" : "steve", "age" : 21, "email" : "steve@example.com" }
{ "_id" : 6, "name" : "james", "age" : 24, "email" : "james@example.com" }
{ "_id" : 7, "name" : "greg", "age" : 23, "email" : "greg@example.com" }

MongoDB $sort Example

In this section, we’ll show some examples of the sort aggregation in MongoDB. We’ll perform our $sort against the documents in the collection we just created.

MongoDB Ascending $sort

Let’s begin by performing an ascending $sort. To do this, we use the following command:

1
2
3
4
5
db.student.aggregate(
   [
     { $sort : { age : 1} }
   ]
)

The output of this command should look like the following:

1
2
3
4
5
6
7
{ "_id" : 1, "name" : "rommel", "age" : 21, "email" : "rommel@example.com" }
{ "_id" : 5, "name" : "steve", "age" : 21, "email" : "steve@example.com" }
{ "_id" : 3, "name" : "jokoy", "age" : 22, "email" : "jokoy@example.com" }
{ "_id" : 4, "name" : "dan", "age" : 22, "email" : "dan@example.com" }
{ "_id" : 7, "name" : "greg", "age" : 23, "email" : "greg@example.com" }
{ "_id" : 2, "name" : "joseph", "age" : 24, "email" : "joseph@example.com" }
{ "_id" : 6, "name" : "james", "age" : 24, "email" : "james@example.com" }

MongoDB Descending $sort

Next, let’s try a descending $sort:

1
2
3
4
5
db.student.aggregate(
   [
     { $sort : { age : -1} }
   ]
)

This time, the output should look something like this:

1
2
3
4
5
6
7
{ "_id" : 2, "name" : "joseph", "age" : 24, "email" : "joseph@example.com" }
{ "_id" : 6, "name" : "james", "age" : 24, "email" : "james@example.com" }
{ "_id" : 7, "name" : "greg", "age" : 23, "email" : "greg@example.com" }
{ "_id" : 3, "name" : "jokoy", "age" : 22, "email" : "jokoy@example.com" }
{ "_id" : 4, "name" : "dan", "age" : 22, "email" : "dan@example.com" }
{ "_id" : 1, "name" : "rommel", "age" : 21, "email" : "rommel@example.com" }
{ "_id" : 5, "name" : "steve", "age" : 21, "email" : "steve@example.com" }

We can see that the value of the age field was indeed sorted in descending order from highest to lowest.

Conclusion

Understanding the stages of the aggregation pipeline will ensure that you perform aggregation operations correctly in MongoDB. In this article, we learned about the $sort stage of the pipeline. We discussed the syntax and purpose of the sort aggregation in MongoDB, and we looked at some examples of its use. If you’ve followed along with the steps outlined in this tutorial, you’ll be ready to implement the sort aggregation in your own MongoDB database.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.