MongoDB aggregation framework provides a way to process and transform data that is stored in our MongoDB collections. It allows you to perform calculations and return the calculated results using various data aggregation tools such as aggregation pipelines, map-reduce functions, or single-purpose aggregation methods.
Here are some of the most important concepts of MongoDB Aggregation:
Example of a simple aggregation pipeline:
db.collection.aggregate([
{ $match: { status: 'A' } },
{ $group: { _id: '$cust_id', total: { $sum: '$amount' } } },
{ $sort: { total: -1 } },
]);
Each item in the pipeline is a stage. The first stage is a $match
stage that filters the documents in the collection. The second stage is a $group
stage that groups the documents by the cust_id
field and calculates the sum of the amount
field. The third stage is a $sort
stage that sorts the documents by the total
field in descending order.