πŸƒDBQuestpractice MongoDB queries
0 / 110

MongoDB aggregation basics: $match and $project

$match, $project, $addFields, $count, $sort, $limit.  Β·  8 practice questions  Β·  Cheat sheet ↓

An aggregation pipeline is an array of stages; each stage takes the documents from the previous one and passes on a new set. $match filters exactly like a find() filter and belongs as early as possible. $project builds the output shape and can compute new fields with expressions such as $multiply or $concat. $addFields computes too but keeps every existing field. $sort, $limit and $count do what their names say, in the order you place them.

This is MongoDB aggregation pipeline practice at the stage level: no grouping yet, just getting comfortable with "$field" references, expression operators and the fact that stage order is literal. A $limit before a $sort limits first, unlike the cursor methods. Once these stages feel natural, $group and $unwind are small steps.

MongoDB aggregation pipeline practice questions

  1. Using the aggregation pipeline, return name and cuisine (no _id) for Manhattan restaurants. easy restaurants
  2. Count how many restaurants are in Queens, using a pipeline that outputs a field called total. easy restaurants
  3. For every restaurant output name and a computed field capacityScore equal to seats multiplied by price. No _id. medium restaurants
  4. Add a field gradeCount (the number of grade entries) to every restaurant while keeping all original fields. medium restaurants
  5. Return the 3 restaurants with the most seats. Output name and seats only, no _id. medium restaurants
  6. Output each restaurant's name and its cuisine in UPPERCASE as a field called shout. No _id. medium restaurants
  7. For movies released in 2020 or later, output title, year, and a boolean isLong that is true when runtime exceeds 120 minutes. No _id. hard movies
  8. Output name and avgScore – the average of each restaurant's grade scores – for restaurants in Brooklyn. No _id. hard restaurants

Each question is answered in a live mongo-shell editor on this page; the result is checked against a reference solution.

$match, $project and $addFields cheat sheet

A pipeline is an array of stages

db.restaurants.aggregate([
  { $match:   { borough: "Manhattan" } },
  { $project: { _id: 0, name: 1, cuisine: 1 } },
  { $sort:    { name: 1 } },
  { $limit:   5 }
])

Each stage takes the previous stage's documents and emits new ones.

$match is find's filter

Same syntax exactly. Put it first – it is the only stage that can use an

index, and everything after it does less work.

$project computes, not just selects

{ $project: {
    _id: 0,
    name: 1,
    capacityScore: { $multiply: ["$seats", "$price"] },
    shout: { $toUpper: "$cuisine" }
} }

Field references are strings starting with $.

$addFields keeps everything else

{ $addFields: { gradeCount: { $size: "$grades" } } }

Use $addFields (alias $set) when you want to add a field;

$project when you want to replace the whole shape.

$count

{ $count: "total" }   // => [ { total: 12 } ]

Common questions

What's the difference between $project and $addFields?

$project decides the exact output: fields you do not list (apart from _id) are dropped. $addFields (alias $set) adds or overwrites the fields you list and keeps everything else. Use $addFields to compute, $project to trim.

Why does "$seats" need the dollar sign?

Inside aggregation expressions a bare string is a literal. "$seats" means the value of the seats field of the current document; "seats" is just the word seats. The same applies to nested paths: "$address.zipcode".

Should $match go first in a pipeline?

Yes, whenever it can. An early $match shrinks the documents every later stage must process and can use indexes, which later stages cannot. A $match placed after $group is the aggregation equivalent of SQL's HAVING.

Continue:← Embedded DocumentsGrouping & Accumulators β†’

MongoDB topics:Finding & ProjectionComparison OperatorsLogical OperatorsElement & TypePattern MatchingSort, Limit & SkipArray QueriesEmbedded DocumentsGrouping & Accumulators$unwind & Array PipelinesJoins & Advanced StagesFull cheat sheet