Loading lessons...
$sort and $project
$sort and $project
$sort orders documents, and $project picks which fields are passed along - the same idea as projection in find().
$sort - order the documents
// Highest accommodates first
db.listingsAndReviews.aggregate([{ $sort: { accommodates: -1 } }])
1sorts ascending (A to Z, low to high).-1sorts descending (high to low).- Sort by multiple fields by adding more pairs:
{ $sort: { category: 1, likes: -1 } }.
$project - choose the fields
db.restaurants.aggregate([
{ $project: { name: 1, cuisine: 1, address: 1 } },
{ $limit: 5 }
])
1includes a field,0excludes it._idis always included unless you explicitly set_id: 0.- You cannot mix
0and1in the same$project, except for_id.
Combine them for a top-N view
db.listingsAndReviews.aggregate([
{ $sort: { accommodates: -1 } },
{ $project: { name: 1, accommodates: 1 } },
{ $limit: 5 }
])
TL;DR
$sort:1= ascending,-1= descending.$projectpicks fields (1 = include, 0 = exclude)._idis included unless excluded; don't mix 1s and 0s.