Mongoose Sort Multiple Fields

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

Introduction

Sorting is an important part of programming. We use sorting in development also. While working with databases, sorting is often used with data retrieval. In a MongoDB collection, there can be hundreds of documents. While using data retrieving methods, such as find(), we may wish to get them in sorted order. For example, if a collection contains the data of employees of a company and we want to retrieve all the documents, but sorted according to the values of the age field. In mongoose, we can sort the result in ascending as well as in descending order. The method used for sorting is the sort() method. But the sort() method is not limited to a single field. We can sort the result even by multiple fields. In this article, we will discuss how to perform a query in Mongoose and sort by multiple fields.

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

sort() method

To understand sorting with multiple fields, we first need to understand the situation in the collection. Below is the details collection on which we will perform sorting.

1
2
3
4
5
6
7
> db.details.find()
{ "_id" : ObjectId("5dc3093096f19d4cc2f1b660"), "name" : "John", "age" : 23, "experience" : 2 }
{ "_id" : ObjectId("5dc30a2f96f19d4cc2f1b661"), "name" : "Sam", "age" : 21, "experience" : 1 }
{ "_id" : ObjectId("5dc30a4896f19d4cc2f1b662"), "name" : "Lisa", "age" : 23, "experience" : 4 }
{ "_id" : ObjectId("5dc30a5a96f19d4cc2f1b663"), "name" : "Max", "age" : 27, "experience" : 6 }
{ "_id" : ObjectId("5dc30a6c96f19d4cc2f1b664"), "name" : "Sunny", "age" : 25, "experience" : 3 }
>

We will sort this collection in accordance with two fields – age and experience. So, we aim to sort the documents in ascending order according to the value of the age field. That means, younger to older employees in the result. But if there are multiple employees of the same age, then we will sort them according to the value of the experience field in descending order. So let’s start.

The following route handler will be invoked when the endpoint ‘/find’ will be executed.

1
2
3
4
5
6
7
8
9
router.route("/find").get(function(req, res) {
  details.find({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Currently, this handler retrieves all the documents present in the details collection without any sorting. So let’s attach the sort method and for the time being, just sort the result according to their ages in the ascending order.

1
2
3
4
5
6
7
8
9
details
  .find({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  })
  .sort({ age: 1 });

https://gyazo.com/deb91b40d4662f2546c2387c281d8d13 Image from Gyazo

Before we move further, just have a look at the documents where the name is John and Lisa. The value of the age field is the same in both the documents, that is why they are placed according to their insertion order only. But the values of their experience fields are different, and as mentioned earlier when the values of age fields are the same, the documents will be sorted in descending order according to the values of the experience fields. Let’s do it.

Just add the experience field after the age field and set its value to -1 for descending order.

1
.sort({"age" : 1, "experience": -1})

So what happens now? First, the sort() method will sort the documents in ascending order according to values of the age field, and when two or more documents have the same value for the age field, it will sort only those documents in descending order according to the values of their experience field. Let’s check using the postman.

Image from Gyazo

Check the documents where the name is John and Lisa. This time, they are sorted according to the values of their experience fields. This is how the sort() method works with multiple fields.

Conclusion

Thank you for joining this tutorial on how to use Mongoose to sort a query by multiple fields.

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.