$Facet in MongoDB for multi-output aggregation.
๐ก Introduction: What is $facet
in MongoDB?
When working with large-scale data, you often need to perform multiple analyses or aggregations in parallel. MongoDB’s $facet
stage in the aggregation pipeline is a powerful operator that allows you to generate multiple outputs from a single aggregation query, efficiently and in a well-organized manner.
๐ Understanding $facet
: The Power of Multi-Pipeline Aggregation
-
$facet
is an aggregation stage that allows you to run multiple sub-pipelines in parallel. -
Each sub-pipeline operates on the same input data and produces a separate result.
-
The final output is a single document with fields corresponding to each pipeline.
๐ธ Use cases:
-
Pagination + total count in one query
-
Summary statistics + filtered results
-
Charts and reports generation from the same dataset
๐งฑ Syntax of $facet
{
$facet: {
<outputField1>: [ <stage1>, <stage2>, ... ],
<outputField2>: [ <stage1>, <stage2>, ... ],
...
}
}
Each key in the $facet
object defines a sub-pipeline and its stages.
๐งฐ Step-by-Step: Using $facet
in Practice
๐ Step 1: Sample Data
Let’s say we have a products
collection:
{
"_id": 1,
"category": "Electronics",
"price": 199.99,
"rating": 4.5
}
๐ Step 2: Create an Aggregation Pipeline with $facet
๐ฏ Goal:
-
Get average price by category
-
Get top 3 high-rated products
๐ง Aggregation Query:
db.products.aggregate([
{
$facet: {
"AveragePriceByCategory": [
{ $group: { _id: "$category", avgPrice: { $avg: "$price" } } }
],
"TopRatedProducts": [
{ $sort: { rating: -1 } },
{ $limit: 3 }
]
}
}
])
๐ผ️ Output:
{
"AveragePriceByCategory": [
{ "_id": "Electronics", "avgPrice": 199.99 }
],
"TopRatedProducts": [
{ "_id": 2, "category": "Books", "price": 19.99, "rating": 5.0 },
...
]
}
๐ผ️ (Optional: Insert a diagram showing the data flow through multiple pipelines inside $facet
)
๐ Future Scope
-
Dashboards & Analytics: Use
$facet
to generate multiple chart data in a single query. -
Performance Optimization: Instead of firing multiple queries,
$facet
runs everything in one pass. -
Combined Filtering and Reporting: Apply filters before the
$facet
to limit processed data. -
Integration with BI Tools: Efficient multi-result pipelines help in real-time analytics.
Good knowledge got about the monogodb multi-output aggregation ♥️
ReplyDeleteThe knowledge throw this blog is amazing really loved the way you did mongodb
ReplyDelete