Mongodb Aggregation Pipeline
MongodbAggregation Pipeline consist of stages and each stage transforms the
document. Aggregation applies only on complex Queries.
It is a multi-stage pipeline and in each state and the documents are taken as input
to produce the resultant set of documents.
In the next stage (ID available) the resultant documents are taken as input to
produce output, this process continues till the last stage.
The basic pipeline stages are defined below:
Filters (Stages) that will operate like queries.
The document transformation that modifies the resultant document.
Pipeline provides for matching, grouping,Projecting and sorting documents.
2.
There are threetypes of aggregations:
1) Aggregate pipelines.
2) Map-Reduce aggregations.
3) Single purpose Evalutionary Query aggregations.
3.
Stages: Aggregation stagesdefine the various operations applied to the
documents in the ipeline. Some common stages include:
• $match : Filters documents based on specified criteria.
• $group : Groups documents by a specified key and allows you to perform
aggregate functions on the grouped data.
• $project : Reshapes documents, specifying which fields to include or
exclude.
• $sort : Sorts the documents based on one or more fields (1 or -1).
• $limit : Limits the number of documents passed to the next stage.
• $skip : Skips a specified number of documents.
• $unwind : Deconstructs an array field, producing a separate document for
each array element.
• $lookup: Combines two collections or Collection related documents.
4.
• Let usdiscuss the aggregation pipeline with the help of an example:
5.
Explanation:
• In theabove example the collection is train, $match stage filters the
documents by the value in class field i.e. class: “first-class” in the first
stage and passes the document to the second stage.
• In the Second Stage, the $group stage groups the documents by the id field
to calculate the sum of fare for each unique id.
• Here, the aggregate() function is used to perform aggregations. It can have
three operators Stages , Expression and Accumulator. These operators
work together to achieve final desired output.