Lesson 20 +10 XP

$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 } }])
  • 1 sorts ascending (A to Z, low to high).
  • -1 sorts 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 }
])
  • 1 includes a field, 0 excludes it.
  • _id is always included unless you explicitly set _id: 0.
  • You cannot mix 0 and 1 in 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.
  • $project picks fields (1 = include, 0 = exclude).
  • _id is included unless excluded; don't mix 1s and 0s.