limit and skip: Taking Part of the Results
"The three movies with the most votes" needs two steps: sort by votes, then keep only the first three. .limit() keeps the first results and drops the rest:
db.movies.find(
{},
{ _id: 0, title: 1, votes: 1 }
).sort({ votes: -1 }).limit(3)
Output:
[
{ title: 'Inception', votes: 2400 },
{ title: 'Interstellar', votes: 2100 },
{ title: 'Parasite', votes: 1800 }
]
Always sort before you limit. Without a sort, limit keeps whichever three documents come first, and that order is not promised.
.skip() jumps over some results first. Together, skip and limit give you pages of results. Here is the second page of three:
db.movies.find(
{},
{ _id: 0, title: 1, votes: 1 }
).sort({ votes: -1 }).skip(3).limit(3)
Output:
[
{ title: 'La La Land', votes: 1700 },
{ title: 'Whiplash', votes: 1500 },
{ title: 'Dunkirk', votes: 1300 }
]
These are the movies in places four to six. MongoDB always skips before it limits, even if you write .limit() first. Writing sort, skip, then limit matches the order the steps happen.
In the exercise, find the three movies with the fewest votes.