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.
Aggregation Commands
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.
Contact Us