Aggregations in Mongo DB


Aggregations in Mongo DB

In MongoDB, aggregate operations process records/documents and return calculated results. It collects values from different documents, groups them, performs various operations on this grouped data, such as sum, mean, min, and max, and returns the calculated results. This is similar to an aggregate function in SQL.

MongoDB provides three ways to perform aggregation:

  • Aggregate pipeline
  • MapReduce function
  • Single-purpose aggregation

Aggregate pipeline In MongoDB, the aggregate pipeline consists of stages, each stage transforming the document. In other words, the aggregate pipeline is a multi-step pipeline, so in each state, the document is taken as input, the resulting document set is generated, and the resulting document is taken in the next stage (id is available). They produce output as input, which causes this process to run to the final stage. The basic pipeline stage provides filters that act like queries, document transformations modify the resulting document, and other pipelines offer tools for grouping and sorting documents. You can also use an aggregate pipeline with a fragmented collection. Phases:

Each phase begins with the next phase operator.

$ match: Used to filter documents to reduce the set of documents specified as input for the next stage.

$ project: Used to select a specific field from the collection.

$ group: Used to group documents based on specific values.

$sort: It is used to sort the document that is rearranging them

$skip: It is used to skip n number of documents and passes the remaining documents

$limit: It is used to pass the first n number of documents, thus limiting them.

$limit: It is used to pass the first n number of documents, thus limiting them.

$out: It is used to write resulting documents to a new collection Expressions:

It refers to the name of the field in input documents for e.g. { $group : { _id : “$id“, total:{$sum:”$fare“}}} here $id and $fare are expressions.

Accumulators: These are used in the group stage

sum: It sums numeric values for the documents in each group count: It counts the total number of documents

avg: It calculates the average of all given values from all documents

min: It gets the minimum value from all the documents

max: It receives the maximum value from all the documents first: It receives the first document from the grouping last: It gets the previous document from the grouping