Use Mongoose to Sort by Multiple Field

Introduction

Sorting is always helpful. Sorting documents of a collection can be useful. Using mongoose, we can get an output where all the documents are sorted in an order. The order can be ascending or descending. We can specify the order. The documents can be sorted according to a single field or even, we can sort documents according to multiple fields. In this article, we will discuss how to use sort method in mongoose.

sort()

We will sort the details collection using the sort() method.

{ "_id" : ObjectId("5d7c854f3082c755d49b5f15"), "name" : "John", "age" : 25, "location" : "Washington DC" }
{ "_id" : ObjectId("5d7c855b3082c755d49b5f16"), "name" : "Sam", "age" : 22, "location" : "Texas" }
{ "_id" : ObjectId("5d7c856b3082c755d49b5f17"), "name" : "Max", "age" : 21, "location" : "Chicago" }
{ "_id" : ObjectId("5d7c85843082c755d49b5f19"), "name" : "Ronn", "age" : 28, "location" : "Detroit" }
{ "_id" : ObjectId("5d7c85f03082c755d49b5f1a"), "name" : "Lisa", "age" : 25, "location" : "Texas" }

Observe the following function.

router.route("/getDocuments").get(function(req, res) {
  detail
    .find({}, function(err, result) {
      if (err) {
        console.log(err);
      } else {
        res.json(result);
      }
    })
    .sort({ age: 1 });
});

Whenever this URL – ‘/getDocuments’, will be used, the above function will be invoked. In the function, we used the sort method. But before we use the sort method, we need a find method that will return the documents. The sort() method is attached with it.

In the function above, first we retrieve all the documents from the details collection using the find method. Then we attached the sort method with it.

.sort({age: 1})

We have to pass an object as the argument. The object has the fields according to which the resulting documents will be sorted. In the function above, we passed this object – {age : 1}. This denotes, the documents will be sorted according to the age in ascending order. The value “1” is used to sort in ascending order and “-1” is used to sort in descending order.

Let’s test it using the postman tool.

Image from Gyazo

We can see the documents are sorted in an ascending order according to the value of the age field.

sorting using multiple fields

Yes! we can sort using multiple fields too. We can specify any number of fields in the object we are passing to the sort method. But the sorting is done in a specific order when there are multiple fields. Let’s understand this with the help of an example. But first look at the following to documents that were sorted earlier.

Image from Gyazo

The age field in both the documents have same value. When we sorted specifying the age, these two fields were placed in order of their insertion. Here, we can sort these two documents using one more field.

.sort({age: 1, location: 1})

Now, along with the age field, we also specified the location field. What will happen? First, all the documents will be sorted in ascending order according to the values of the age field. The documents, where the age is same, will be sorted according the second field, i.e. location. Let’s add this object to our function.

router.route("/getDocuments").get(function(req, res) {
  detail
    .find({}, function(err, result) {
      if (err) {
        console.log(err);
      } else {
        res.json(result);
      }
    })
    .sort({ age: 1, location: 1 });
});

Let’s test it.

Image from Gyazo

We can see, the documents where the value of the age field is same, are sorted according to their locations.

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.