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
- Using the aggregation pipeline, return
nameandcuisine(no_id) for Manhattan restaurants. easy restaurants - Count how many restaurants are in
Queens, using a pipeline that outputs a field calledtotal. easy restaurants - For every restaurant output
nameand a computed fieldcapacityScoreequal toseatsmultiplied byprice. No_id. medium restaurants - Add a field
gradeCount(the number of grade entries) to every restaurant while keeping all original fields. medium restaurants - Return the 3 restaurants with the most
seats. Outputnameandseatsonly, no_id. medium restaurants - Output each restaurant's
nameand itscuisinein UPPERCASE as a field calledshout. No_id. medium restaurants - For movies released in 2020 or later, output
title,year, and a booleanisLongthat is true whenruntimeexceeds 120 minutes. No_id. hard movies - Output
nameandavgScoreβ the average of each restaurant's grade scores β for restaurants inBrooklyn. 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?
"$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?
$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