Introduction to Aggregation
The Aggregation Framework is a powerful feature of MongoDB that allows for data transformation, filtering, and analysis. In this guide, we'll explore advanced techniques using the Aggregation Framework to perform complex operations.
1. `$group` Stage
The `$group` stage is used to group documents based on specified criteria. Here's an example of using the `$group` stage to calculate the average price of products:
db.products.aggregate([
{
$group: {
_id: "$category",
avgPrice: { $avg: "$price" }
}
}
]);
2. `$lookup` Stage
The `$lookup` stage is used to perform a left outer join between two collections. It's handy for combining data from different sources. Here's an example of using the `$lookup` stage:
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "product"
}
}
]);
3. `$unwind` Stage
The `$unwind` stage is used to deconstruct arrays within documents, enabling further analysis. Here's an example of using the `$unwind` stage:
db.sales.aggregate([
{
$unwind: "$items"
}
]);
4. `$facet` Stage
The `$facet` stage allows you to perform multiple aggregation pipelines and return their results as an array. It's useful for running several operations in parallel. Here's an example of using the `$facet` stage:
db.collection.aggregate([
{
$facet: {
stage1: [/* Aggregation pipeline 1 */],
stage2: [/* Aggregation pipeline 2 */],
}
}
]);
Conclusion
The Advanced Aggregation Framework in MongoDB provides a rich set of tools for data analysis and transformation. By mastering techniques like `$group`, `$lookup`, `$unwind`, and `$facet`, you can perform complex operations on your data. Experiment with these stages to unlock the full potential of MongoDB's Aggregation Framework.