MongoDB Aggregation Framework

MongoDB Aggregation Framework is a powerful feature or tool that is used for processing data and analyzing the operation. In conventional data queries, we retrieve data first, then process the data. 

In the case of MongoDB aggregation, data processing, grouping, filtering, and computing is performed in the database before retrieving the data.

The aggregation framework consists of pipeline stages and each stage performs a specific operation. 

Aggregation is the same as pipeline, we can transform the documents into a small group of documents.

db.collectionName.aggregate(pipelineoptions)

db.collectionName.aggregate(pipeline, { allowDiskUse : true })

  • where collectionName – is the name of a collection,
  • pipeline – is an array that contains the aggregation stages,
  • options – optional parameters for the aggregation 

Aggregation pipeline syntax:

pipeline = [
        { $match : { … } },
        { $group : { … } },
        { $sort : { … } }
       ]

💢 Aggregate() method:

The aggregation framework uses a special method called aggregate();

Process documents during aggregation and pass through the stages.

💧 Syntax: 

db.<collection>.aggregate([ <stage1>, <stage2>, ...<stageN>])

💧 Explanation:

  • aggregate() holds the array of stages as a parameter.
  • Each stage is an object. All stages are separated by a comma.
  • All documents in the collection are passed to stage 1, and the documents are processed here. The result of processing is passed to stage 2.
  • Stage 2 takes the documents from Stage 1, performs each operation, and passed them to the next stage, and so on.
  • When the last stage, the result returns back to the client. The results are returned as a cursor from the server.
  • db.collection.aggregate([ ]) is the same as db.collection.find({});

💖 Aggregation stage:

  • Each stage takes the document as an input and outputs the document that may be the same document / limited document / reordered document / new document. 
  • Then output documents will pass to the next stage and so on. Thus eventually, the output will go to the client.
  • One stage does not impact the other stage, stages are independent.
  • In the first stage, all the documents passed to the stage.
Syntax:
Each stage starts with the stage operator. The stage operator is denoted by the $ sign.
                {$<stageOperator> : { }};

  • Each stage will hold an object as its value.
  • Some stage lists of the aggregation framework:
  • $match, $group, $project, $sort, $count, $limit, $skip, $out

💖 Aggregation Expression:

Aggregation expression refers to the field name of the input documents. Aggregation expression must be quoted with double quotes.

Syntax: 

"$fieldName"

Example: 

    {$group: {_id: "$age"}}

For nested document =>

    {$group: {_id: "$company.location.country"}}


Post a Comment

Previous Post Next Post