sort: Ordered Results
find does not promise any order. In our small collection, documents come back in the order they were added, but you should not depend on that. When order matters, add .sort() after the find:
db.movies.find(
{},
{ _id: 0, title: 1, votes: 1 }
).sort({ votes: 1 })
Output:
[
{ title: 'First Man', votes: 800 },
{ title: 'Okja', votes: 900 },
{ title: 'Dunkirk', votes: 1300 },
{ title: 'Whiplash', votes: 1500 },
{ title: 'La La Land', votes: 1700 },
{ title: 'Parasite', votes: 1800 },
{ title: 'Interstellar', votes: 2100 },
{ title: 'Inception', votes: 2400 }
]
The sort document names a field and a direction. 1 sorts from smallest to largest, and -1 sorts from largest to smallest. Text sorts in alphabetical order.
Keep .sort( on the same line as the ) before it. The shell runs a line as soon as it is complete. If .sort(...) starts on a new line, the first line runs without sorting, and the next line gives an error.
You can sort by more than one field. The first field decides the order. The second field is used only when two documents have the same value in the first field:
db.movies.find(
{},
{ _id: 0, title: 1, director: 1, year: 1 }
).sort({ director: 1, year: -1 })
Output:
[
{ title: 'Parasite', director: 'Bong Joon-ho', year: 2019 },
{ title: 'Okja', director: 'Bong Joon-ho', year: 2017 },
{ title: 'Dunkirk', director: 'Christopher Nolan', year: 2017 },
{ title: 'Interstellar', director: 'Christopher Nolan', year: 2014 },
{ title: 'Inception', director: 'Christopher Nolan', year: 2010 },
{ title: 'First Man', director: 'Damien Chazelle', year: 2018 },
{ title: 'La La Land', director: 'Damien Chazelle', year: 2016 },
{ title: 'Whiplash', director: 'Damien Chazelle', year: 2014 }
]
The directors are in alphabetical order. Each director's movies are sorted from newest to oldest.
A second sort field also helps with ties. When two documents have the same value, MongoDB does not promise which one comes first. If you add a second field, such as title, the order is always the same.
In the exercise, sort the movies from best rated to worst, and use the title to break ties.