MongoDB MongoDB Aggregation Framework 1 — Questions and Answers
Question 1: Which aggregation stage filters documents to pass only those matching specified conditions to the next stage?
- $group
- $project
- $match (Correct answer)
- $filter
Correct answer: $match
$match acts like a WHERE clause, filtering documents based on specified criteria before passing them to the next pipeline stage.
Question 2: What is the primary purpose of the $group stage in aggregation?
- To join multiple collections
- To group documents by a specified identifier and compute aggregate values (Correct answer)
- To sort documents into groups
- To create new collections
Correct answer: To group documents by a specified identifier and compute aggregate values
$group groups input documents by a specified _id expression and can apply accumulator expressions like $sum and $avg.
Question 3: Which aggregation accumulator returns the sum of numeric values in a group?
- $total
- $add
- $sum (Correct answer)
- $count
Correct answer: $sum
$sum returns the sum of all numeric values, and when used as $sum: 1, it counts the number of documents in the group.
Question 4: What does the $project stage do in an aggregation pipeline?
- Creates a new database projection
- Passes documents with requested fields to the next stage (Correct answer)
- Projects future data trends
- Adds geospatial projections
Correct answer: Passes documents with requested fields to the next stage
$project reshapes each document by including, excluding, or adding fields before passing documents to the next stage.
Question 5: Which stage limits the number of documents passed to the next aggregation stage?
- $skip
- $restrict
- $limit (Correct answer)
- $max
Correct answer: $limit
$limit passes only the specified number of documents to the next stage, useful for top-N queries.
Question 6: What is the purpose of the $unwind stage in aggregation?
- Deconstructs an array field to output one document per array element (Correct answer)
- Reverses a previous sort
- Unwraps nested objects into flat documents
- Removes duplicate documents
Correct answer: Deconstructs an array field to output one document per array element
$unwind deconstructs an array field, creating a separate output document for each array element.
Which aggregation stage filters documents to pass only those matching specified conditions to the next stage?