MongoDB Aggregation

When MongoDB users want to gather computed data from various documents like sum, average, minimum, maximum, etc from a MongoDB database, MongoDB aggregation can be used. The concept of aggregation mainly clusters out your data from multiple different documents which are then used to perform different types of operations.

In MongoDB there are three ways to perform aggregation :

  • Aggregation pipeline
  • Map-reduce function
  • Single-purpose aggregation methods

Aggregation pipeline

In MongoDB, the aggregation pipeline consists of many stages and each stage transforms the document. In each stage, it takes some documents as input and produces a result as a set of documents. In the next stage, it takes the previous result as input and produces a result. This process continues till the last stage.

There are many stages in MongoDB. Each stage starts with a stage operator. Some stage operators are given below -

$match: It is used for filtering the documents. It can reduce the number of documents that are given as input to the next stage.

$group: It is used to group multiple documents

$sort: It is used to sort documents.

$skip: It is used to skip n number of documents.

$limit: It is used to pass the first n number of documents.

Map Reduce Function

To aggregate, a large amount of data Map-Reduce function can be used. The map-Reduce function has two functions which are map and reduce. The map function makes a group of all the documents and the reduce function perform an operation on those grouped documents.

Single-purpose aggregation methods

Single Purpose Aggregation aggregate all the documents from a single collection in MongoDB. It is used when we need simple access to document like counting the number of documents or for finding all distinct values in a document. It cannot provide flexibility and capability like map-reduce and aggregation pipeline.

22