Dec 08, 2020    Janaki Mahapatra, Mongo

Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. MongoDB provides three ways to perform aggregation

  • Aggregation Pipeline
  • Map-Reduce
  • Single Purpose Aggregation Operations

1. Aggregation Pipeline

  • $project: The $project function in MongoDB passes along the documents with only the specified fields to the next stage in the pipeline. This may be the existing fields from the input documents or newly computed fields
  • $match: This operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.
  • $redact: This operator can change and gives a new form of each document in the stream by restricting the content for each document based on information stored in the documents themselves.
  • $unwind: This operator is used to deconstructs an array field from the input documents to output a document for each element.
    Every output document is the input document with the value of the array field replaced by the element.
  • $group: The MongoDB $group stages operator groups the documents by some specified expression and groups the document for each distinct grouping. An _id field in the output documents contains the distinct group by key. The output documents can also contain computed fields that hold the values of some accumulator expression grouped by the $group‘s _id field. This operator does not order its output documents.
  • $out: The MongoDB $out write the resulting document of the aggregation pipeline to a specified collection. The $out operator must be the last stage in the pipeline. The $out operator lets the aggregation framework return result sets of any size.


   { $match: { status: "A" } },
   { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }

2. Map-Reduce:
Map-reduce uses custom JavaScript functions to perform the map and reduce operations, as well as the optional finalize operation.