Open In App

Aggregation Commands

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB’s aggregation commands are a powerful feature of its database it allowing users to perform complex operations on their data. These commands are part of the aggregation pipeline framework which consists of stages that can perform operations like grouping, sorting, filtering and applying expressions to data. By using these commands developers can generate reports, summarize data, and gain insights from large datasets.

In this article, We will learn about Aggregation Commands and their different types along with the help of examples and so on.

Understanding Aggregation Commands

  • Aggregation commands in MongoDB are part of the aggregation pipeline framework.
  • They allow for operations like grouping, sorting, filtering and applying expressions to data.
  • The aggregation pipeline consists of stages each performing a specific operation on the data.
  • Aggregation commands can be used for tasks such as calculating totals, averages and other statistical operations.
  • They are useful for generating reports, summarizing data and gaining insights from large datasets.
  • Aggregation commands can also be used to join data from multiple collections or perform complex data manipulations.

Common Aggregation Commands

MongoDB provides several aggregation commands to perform different types of operations. Let’s understand some of the most commonly used commands:

To understand Common Aggregation Commands we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called products which contains information like name, price, category and quantity of the products in various documents.

[
{
"name": "Product A",
"price": 150,
"category": "Category 1"
},
{
"name": "Product B",
"price": 200,
"category": "Category 2"
},
{
"name": "Product C",
"price": 120,
"category": "Category 1"
},
{
"name": "Product D",
"price": 180,
"category": "Category 2"
}
]

1. $match

The $match command filters documents based on specified criteria, similar to the find() method. It allows users to select only those documents that match the given conditions.

Example:

To retrieve products with a price greater than $100, we can use the $match command:

db.products.aggregate([
{ $match: { price: { $gt: 100 } } }
])

Output:

[
{
"_id": "Category 1",
"total_products": 2
},
{
"_id": "Category 2",
"total_products": 2
}
]

2. $group

The $group command groups documents together based on a specified key and applies aggregate functions to the grouped data, such as sum, count or average.

Example

Continuing with the products collection example, let’s group products by their category and calculate the total number of products in each category:

db.products.aggregate([
{ $group: { _id: "$category", total_products: { $sum: 1 } } }
])

Output:

[
{ "_id": "Category 1", "total_products": 2 },
{ "_id": "Category 2", "total_products": 2 }
]

3. $project

The $project command reshapes documents by including, excluding, or renaming fields. It allows users to define the structure of the output documents.

Example:

Suppose we want to retrieve only the name and price fields of products from the products collection. We can use the $project command to include only these fields in the output:

db.products.aggregate([
{ $project: { _id: 0, name: 1, price: 1 } }
])

Output:

[
{ "name": "Product A", "price": 150 },
{ "name": "Product B", "price": 200 },
{ "name": "Product C", "price": 120 },
{ "name": "Product D", "price": 180 }
]

4. $sort

The $sort command sorts documents based on specified fields in ascending or descending order.

Example:

To retrieve products from the products collection sorted by price in descending order, we can use the $sort command:

db.products.aggregate([
{ $sort: { price: -1 } }
])

Output:

[
{
"name": "Product B",
"price": 200,
"category": "Category 2"
},
{
"name": "Product D",
"price": 180,
"category": "Category 2"
},
{
"name": "Product A",
"price": 150,
"category": "Category 1"
},
{
"name": "Product C",
"price": 120,
"category": "Category 1"
}
]

5. $limit

The $limit command restricts the number of documents returned by an aggregation operation.

Example:

If we want to retrieve only the top 5 highest-priced products from the products collection, we can use the $limit command:

db.products.aggregate([
{ $sort: { price: -1 } },
{ $limit: 3 }
])

Output:

[
{ "name": "Product B", "price": 200, "category": "Category 2" },
{ "name": "Product D", "price": 180, "category": "Category 2" },
{ "name": "Product A", "price": 150, "category": "Category 1" }
]

Combining Aggregation Commands

One of the strengths of MongoDB’s aggregation framework is the ability to chain multiple commands together to perform complex operations.

Example:

Suppose we want to find the average price of products in each category from the products collection. We can achieve this by combining the $group and $project commands:

db.products.aggregate([
{ $group: { _id: "$category", avg_price: { $avg: "$price" } } },
{ $project: { _id: 0, category: "$_id", avg_price: 1 } }
])

Output:

[
{
"category": "Category 1",
"avg_price": 135
},
{
"category": "Category 2",
"avg_price": 190
}
]

This aggregation pipeline first groups products by category, calculates the average price for each category, and then projects the category and average price fields in the output.

Conclusion

Overall, MongoDB’s aggregation commands provide developers with a flexible and powerful toolset for working with data. Whether you need to calculate totals, averages, or perform more complex data manipulations, MongoDB’s aggregation commands offer the functionality needed to handle a wide range of tasks. By understanding these commands effectively and developers can use the MongoDB’s aggregation framework and make the most of their data.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads