How to sort the results of a MongoDB query

For a full overview of MongoDB and all my posts on it, check out my overview.

After using the find method to get retrieve some documents from MongoDB and further trimming down that result using filters, there may still be a lot of data. It may be easier to work with the data if is it sorted using the sort method.

Much like how a user can modify the result of a query by chaining something like the limit method, you can use chain the sort method to the result of another method that returns a result, such as find or limit, to get that data into a specific order.

With the following data set in a collection called users:

{
	"name": "John Doe",
	"email": "test@test.com",
	"admin": false,
	"dateJoined": ISODate("2021-02-01")
},
{
	"name": "Jane Doe",
	"email": "test2@test2.com",
	"admin": false,
	"dateJoined": ISODate("2021-03-01")
},
{
	"name": "Bob Doe",
	"email": "bob@bob.com",
	"admin": true,
	"dateJoined": ISODate("2021-01-01")
},
{
	"name": "Your Mom",
	"email": "koolkid@someplace.com",
	"admin": false,
	"dateJoined": ISODate("2020-12-01")
}

To pull all the documents out sorted by the date they joined in ascending order, we would do the following:

db.users.find().sort({dateJoined: 1})

Notice that sort takes an argument of an object describing how to sort the data. Each field in the object can have a value of 1 (ascending) or -1 (descending)

This will get us the following:

{
	"name": "Your Mom",
	"email": "koolkid@someplace.com",
	"admin": false,
	"dateJoined": ISODate("2020-12-01")
},
{
	"name": "Bob Doe",
	"email": "bob@bob.com",
	"admin": true,
	"dateJoined": ISODate("2021-01-01")
},
{
	"name": "John Doe",
	"email": "test@test.com",
	"admin": false,
	"dateJoined": ISODate("2021-02-01")
},
{
	"name": "Jane Doe",
	"email": "test2@test2.com",
	"admin": false,
	"dateJoined": ISODate("2021-03-01")
}

Sorting on multiple fields can be done as well

db.users.find().sort({admin: 1, name -1})

This will return the documents first sorted in ascending order by admin, then sorted in descending order by name

{
	"name": "Jane Doe",
	"email": "test2@test2.com",
	"admin": false,
	"dateJoined": ISODate("2021-03-01")
},
{
	"name": "John Doe",
	"email": "test@test.com",
	"admin": false,
	"dateJoined": ISODate("2021-02-01")
},
{
	"name": "Your Mom",
	"email": "koolkid@someplace.com",
	"admin": false,
	"dateJoined": ISODate("2020-12-01")
},
{
	"name": "Bob Doe",
	"email": "bob@bob.com",
	"admin": true,
	"dateJoined": ISODate("2021-01-01")
}

Did you find this information useful? If so, consider heading over to my donation page and drop me some support.

Want to ask a question or just chat? Contact me here