$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.


๐Ÿ‘ฉ‍๐ŸŽ“ Name: Sarthak Kulkarni

๐Ÿซ College: Sri Balaji University, Pune

๐Ÿซ School: School of Computer Studies

๐ŸŽ“ Class: TY-BCA(E)

    


Comments

  1. Good knowledge got about the monogodb multi-output aggregation ♥️

    ReplyDelete
  2. The knowledge throw this blog is amazing really loved the way you did mongodb

    ReplyDelete

Post a Comment

Popular posts from this blog

Query Operator's

Creating Documents in MongoDB(Insert)