MongoDB

How to do a MongoDB aggregate group sort

Aggregate is a MongoDB method that processes the data through several operators and methods. In MongoDb, the aggregation is assisted by several methods and operators that can perform different tasks. Among those operators, the $sort operator helps to sort the documents and return the documents in an organized order. And for group sorting in MongoDB, the $group operator is used with the $sort operator. With the help of the $group and $sort operator, MongoDB can also sort the grouped data in ascending or descending order.

In this post, we have provided an informative insight into the aggregate group sort functionality of MongoDB.

How group sorting works in MongoDB

The aggregate method in MongoDB is primarily used to match and group the data by following the syntax of the aggregate function. Furthermore, the grouped data can be sorted then with the help of the “$sort” operator in MongoDB. The sorting can be in any order; “ascending“, “descending” or “textScore“. The following syntax is followed to the group as well as sort the documents:

> db.collection-name.aggregate([

{"$group": {<unique-field>: <group-order>}},

{"$sort": {<field>: <sorting-order>}}

])

The above syntax has two stages:

In the first stage, $group operator groups the data according to <unique-field>

The second stage sorts out the data according to the defined field <field> and the <sorting-order>. The <sorting-order> accepts the value “1” or “-1” for “ascending” or “descending” orders respectively.

How to perform a MongoDB aggregate group sort

To apply aggregate group sort in MongoDB; you must have the following instances on your system. We are working on a Linux-based system and the following instances are used in this tutorial:

– database-name: The name of the database used is “linuxhint“.

– collection-name: The collection name used in this tutorial is referred to as “employees“.

The documents contained by “employees” collection are displayed by using the below-mentioned command:

> db.employees.find().pretty()

Text Description automatically generated
Text Description automatically generated

Example: Use of $group in MongoDB

The $group operator in MongoDB can be used to group the data according to some field. Referring to the content inside the “employees” collection, the command written below groups the data according to the “designation” field.

> db.employees.aggregate([{$group: {_id: "$designation"}}])

Text Description automatically generated

Or you can also count the number of fields in each group. Let’s say, we add a count operation in the above command. So, the following command is the upgraded version of the above command that provides a number of fields in a group:

> db.employees.aggregate([{$group: {_id: "$designation", count: {$sum: 1}}}])

Text Description automatically generated with medium confidence

The aggregate method can provide results with multiple properties.

Example: Use of $sort in MongoDB

The $sort helps to sort the documents in ascending and descending order. The below-mentioned command is used to sort the employees collection in descending order of Salary field:

> db.employees.aggregate([{$sort: {salary: -1}}])

Text Description automatically generated

Example : Use $group and $sort with aggregate()

This example illustrates the usage of $group and $sort on the sample data shown above. We have executed the below mentioned MongoDB command that will perform the following action:

  • Groups the data with respect to designation and $group operator is used to do so.

Note: you can pass “1” value to $sort operator for ascending order)

  • Sorts that grouped data in descending order
> db.employees.aggregate([{$group: {_id: "$designation"}}, {$sort: {_id: -1}}])

Text Description automatically generated

Example: group and sort by count

MongoDB supports an operator $sortByCount that helps to sort the fields by calculating the total number of occurrences. The processing of the $sortByCount operator can be replaced by using the $group and $sort operator. For instance, the below-stated command will exercise the $group and $sort operator in the following way:

  • $group performs the grouping on the “designation” field
  • $sum sums up the number of times a “designation” field occurred. And the value from $sum is returned in a field named as count
  • $sort operator is used to sort the count field in descending order
> db.employees.aggregate([{$group: {_id: "$designation", count: {$sum: 1}}}, {$sort: {count: -1}}])

Text Description automatically generated

Conclusion

MongoDB is a well-known open-source non-relational database and is used widely because of its supported methods and operators. These functions can be used to perform any kind of data processing operation inside a MongoDB database. In this guide, we have learned to group and sort the documents in a collection of MongoDB-based databases. The grouping and sorting phenomena are backed up by the aggregate method of MongoDB. By following this guide, a MongoDB enthusiast can get good hands-on grouping the documents and perform multiple operations on those groups as well.

About the author

Adnan Shabbir