Ticker

6/recent/ticker-posts

Aggregation in MongoDB

Aggregation in MongoDB

Introduction:
Aggregation is a powerful framework provided by MongoDB for processing, transforming, and analyzing data in a more advanced and flexible manner. It allows you to perform operations on a collection's data and get meaningful insights by applying various stages in a pipeline.

Aggregation Pipeline:
The aggregation pipeline in MongoDB consists of multiple stages, each performing a specific operation on the data. Documents are processed through these stages sequentially, and each stage takes the output of the previous stage as its input.

Basic Stages:

  1. $match:

    • Filters the documents based on specified criteria.
    • Syntax:
      javascript
      db.collection.aggregate([
      { $match: { field: value } }
      ]);
  2. $group:

    • Groups documents by a specified key and allows for performing aggregate functions on grouped data.
    • Syntax:
      javascript
      db.collection.aggregate([
      { $group: { _id: "$key", resultField: { $function: "aggregateOperator" } } }
      ]);
  3. $project:

    • Reshapes the documents, including selecting specific fields or adding computed fields.
    • Syntax:
      javascript
      db.collection.aggregate([
      { $project: { field1: 1, field2: 1, computedField: { $function: "expression" } } }
      ]);

Example:
Let's assume we have a collection named "sales" with documents containing "product," "quantity," and "price" fields.

Suppose we want to find the total revenue for each product where the quantity is greater than 10 and then calculate the average revenue. The aggregation query would look like:

javascript
db.sales.aggregate([
{
$match: {
quantity: { $gt: 10 }
}
},
{
$group: {
_id: "$product",
totalRevenue: { $sum: { $multiply: ["$quantity", "$price"] } }
}
},
{
$group: {
_id: null,
averageRevenue: { $avg: "$totalRevenue" }
}
}
]);

Explanation:

  • The $match stage filters out documents where the "quantity" is greater than 10.
  • The $group stage groups the documents by "product" and calculates the total revenue for each group using the $sum operator, which multiplies "quantity" and "price" together for each document.
  • The second $group stage groups all the previous results (now grouped by product) into a single group, calculating the average of the "totalRevenue" field across all products using the $avg operator.

This is a basic example, but the aggregation pipeline can be extended with more stages and complex operations to perform sophisticated data manipulations in MongoDB.

Post a Comment

0 Comments