When working with a MongoDB collection, there will likely be instances when we want to sort our query results by a particular field or set of fields. Conveniently, MongoDB allows us to sort our query results before they are returned to us.
To sort our documents, we must append the .sort()
method to our query. The .sort()
method takes one argument, a document specifying the fields we want to sort by, where their respective value is the sort order.
Take a look at the syntax for sorting a query below:
db.<collection>.find().sort( { <field>: <value>, <second_field>: <value>, … } )
There are two values we can provide for the fields: 1
or -1
. Specifying a value of 1
sorts the field in ascending order, and -1
sorts in descending order. For datetime and string values, a value of 1
would sort the fields, and their corresponding documents, in chronological and alphabetical order, respectively, while -1
would sort those fields in the reverse order.
Let’s look at an example to see the .sort()
method in action. Imagine we are developing an e-commerce site that sells vintage records, and our application needs to retrieve a list of inventoried records by their release year. We could run the following command to sort our records by the year they were released:
db.records.find().sort({ "release_year": 1 });
This query might return the following list of records sorted by their release_year
, in ascending order.
{ _id: ObjectId(...), artist: "The Beatles", album: "Abbey Road", release_year: 1969 }, { _id: ObjectId(...), artist: "Talking Heads", album: "Stop Making Sense", release_year: 1984 }, { _id: ObjectId(...), artist: "Prince", album: "Purple Rain", release_year: 1984 }, { _id: ObjectId(...), artist: "Tracy Chapman", album: "Tracy Chapman", release_year: 1988 } …
It’s important to note that when we sort on fields that have duplicate values, documents that have those values may be returned in any order. Notice in our example above, that we have two documents with the release_year
1984
. If we were to run this exact query multiple times, documents would get returned in numerical order by release_year
, but the two documents that have 1984
as their release_year
value, might be returned in a different order each time.
We can also specify additional fields to sort on to receive more consistent results. For example, we can execute the following query to sort first by release_year
and then by artist
.
db.records.find().sort({ "release_year": 1, "artist": 1 });
This would return a list of matching documents that were sorted first by the release_year
field in ascending order. Then, within each release_year
value, documents would be sorted by the artist
field in ascending order. Our query result would look like this:
{ _id: ObjectId(...), artist: "The Beatles", album: "Abbey Road", release_year: 1969 }, { _id: ObjectId(...), artist: "Prince", album: "Purple Rain", release_year: 1984 }, { _id: ObjectId(...), artist: "Talking Heads", album: "Stop Making Sense", release_year: 1984 }, { _id: ObjectId(...), artist: "Tracy Chapman", album: "Tracy Chapman", release_year: 1988 } …
Notice how the two documents with the release_year
1984
, are now also sorted alphabetically, by the artist
field.
Before moving on, let’s practice using the .sort()
method to sort our queries.
Instructions
Connect to the restaurants
database, then query the listingsAndReviews
collection, to retrieve a list of restaurants where the cuisine
is "Spanish"
. The query results should be sorted by the name
field alphabetically.
Query the same collection, listingsAndReviews
, to return a list of restaurants where the borough
is "Queens"
. The results should be sorted by the address zipcode
field, in descending order.