Skip to main content

πŸ“˜ Structure of an Aggregation Pipeline

To interact with a relational database, we typically use SQL, a 4th-generation language, to access our data. With MongoDB, we instead get data and transform it in incremental steps.

An aggregation pipeline is composed of stages.

We pass an array of stages to the aggregate method like so:

db.mycollection.aggregate([
stage1,
stage2,
stage3
])

Example​

An aggregation pipeline that does the same as the above SQL statement could be:

db.mycollection.aggregate([
{
$sort:
/**
* Provide any number of field/order pairs.
*/
{
num_mflix_comments: -1,
},
},
{
$limit:
/**
* Provide the number of documents to limit.
*/
1,
},
{
$unwind:
/**
* path: Path to the array field.
* includeArrayIndex: Optional name for index.
* preserveNullAndEmptyArrays: Optional
* toggle to unwind null and empty values.
*/
{
path: "$cast",
},
},
{
$project:
/**
* Specifications: The fields to
* include or exclude.
*/
{
cast: 1,
},
},
])