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": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2021-02-01")
},
{
    "name": "Jane Doe",
    "email": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2021-03-01")
},
{
    "name": "Bob Doe",
    "email": "[email protected]",
    "admin": true,
    "dateJoined": ISODate("2021-01-01")
},
{
    "name": "Your Mom",
    "email": "[email protected]",
    "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": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2020-12-01")
},
{
    "name": "Bob Doe",
    "email": "[email protected]",
    "admin": true,
    "dateJoined": ISODate("2021-01-01")
},
{
    "name": "John Doe",
    "email": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2021-02-01")
},
{
    "name": "Jane Doe",
    "email": "[email protected]",
    "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": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2021-03-01")
},
{
    "name": "John Doe",
    "email": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2021-02-01")
},
{
    "name": "Your Mom",
    "email": "[email protected]",
    "admin": false,
    "dateJoined": ISODate("2020-12-01")
},
{
    "name": "Bob Doe",
    "email": "[email protected]",
    "admin": true,
    "dateJoined": ISODate("2021-01-01")
}

18