Mongoose Sort Multiple Fields

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

Introduction

In today’s article, we are going to use Mongoose for sorting elements in MongoDB. But before I move on to the code, let me give you some real-life examples about sorting and how it might be used in a real world application.

The best real-life example of sorting is and e-commerce like Amazon or eBay where there are tons of items for sale. Whenever you search for a product you see options available to sort the products by. Some of the options might be:

  • Low to high price
  • High to Low Price
  • Recent Products
  • Popular Products
  • Highest Review Rating Products

Image from Gyazo

The above sort criteria are just examples and you might have seen some different kind of criteria used to sort the products depending on the type of website. Now let’s get started that how we can implement sorting in mongo DB using Mongoose.

Sorting in Multiple fields MongoDB using Mongoose

Before we sort the documents let’s find out how many documents exist inside our database. To get all the available records, we need to use the find() method from mongoose. Let’s add a little bit of code to our mongoosemodel.js file.

File: mongoosemodel.js

1
2
3
4
5
6
7
8
9
10
11
12
13
var mongoose = require("mongoose");
var userProfile = new mongoose.Schema({
name: { type: String },
age: { type: Number }
});

module.exports = mongoose.model("userProfile", userProfile);
var newUser = mongoose.model("userProfile", userProfile);

const allusers = newUser.find({}, "name age", function(err, docs) {
if (err) console.log(err);
console.log(docs);
});

In the above code, we have imported mongoose using require. After that, we have created a schema which tells what type of data we are going to enter in our database.

Once schema creation finished, we have to create a model to use that schema for insert, retrieve, or to perform any operations with our data in the database.

Note: We have not written code for inserting data inside the database. Instead of inserting the data we are going with the data we have presently in our database. We have already performed insert operation in previous tutorials.

The most important part is here, now we are retrieving all the data from the database. We are using find() method from MongoDB to fetch the data from the database and printing in the console.

Result:

1
2
3
4
5
6
7
8
9
10
11
C:\mongooseproject>npm start
> mongooseproject@1.0.0 start C:\mongooseproject
> node index.js
*** MongoDB got connected ***
Our Current Database Name : mongoosepractice
[
{ _id: 5d49c275e0957b0f70cb91ad, name: 'Eva', age: 21 },
{ _id: 5d49c441b628860f707ad52f, name: 'Sam', age: 23 },
{ _id: 5d49c471b628860f707ad530, name: 'Adam', age: 48 },
{ _id: 5d49c666b628860f707ad531, name: 'Raymond', age: 20 }
]

Image from Gyazo

Let’s finish our goal for this article. Now, we have all the records. To get a sorted a result we need to add another function name sort() from Mongoose.

The code you need to update in mongoosemodel.js file:

1
2
3
4
const allusers = newUser.find({}, "name age", function(err, docs) {
if (err) console.log(err);
console.log(docs);
}).sort([["name", 1], ["age","desc"]]);

In the above code snippet, we have used nested arrays in a sort function, and there we have passed two values on which we want to sort. Sorting can be in ascending or descending order. But there are 6 different keywords that you can use to achieve this task. These keywords can be used as in value pair pattern. You can also see this in the above example.

The keywords or you can say values are: asc desc ascending descending 1 -1

As you can see in the screenshot, the age group is sorted in descending order.

Conclusion

This concludes our tutorial on how to sort multiple fields using Mongoose. We hope you can apply what you’ve seen here for your specific application. Thanks for joining us for another quick demo!

Just The Code

Final Code of mongoosemodel.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var mongoose = require("mongoose");
var userProfile = new mongoose.Schema({
name: { type: String },
age: { type: Number }
});
module.exports = mongoose.model("userProfile", userProfile);
var newUser = mongoose.model("userProfile", userProfile);
const allusers = newUser

.find({}, "name age", function(err, docs) {
if (err) console.log(err);
console.log(docs);
})
.sort([["name", 1], ["age", "descending"]]);

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.