0
0
MongoDBquery~3 mins

Why $facet for multiple pipelines in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could get many answers from your data in one simple step, without extra work or mistakes?

The Scenario

Imagine you have a big box of mixed fruits and you want to sort them into apples, oranges, and bananas separately by hand. You try to count and organize each fruit type one by one, writing down the totals on paper.

The Problem

Doing this by hand is slow and tiring. You might lose track, make counting mistakes, or mix fruits up. Also, if you want to find more details like the biggest apple or the average size of bananas, it becomes even more complicated and error-prone.

The Solution

The $facet stage in MongoDB lets you run multiple sorting and counting tasks at the same time on the same data. It's like having several helpers who each focus on one fruit type and give you all the results together quickly and accurately.

Before vs After
Before
db.fruits.find({ type: 'apple' }).count()
db.fruits.find({ type: 'orange' }).count()
db.fruits.find({ type: 'banana' }).count()
After
db.fruits.aggregate([
  { $facet: {
      apples: [{ $match: { type: 'apple' } }, { $count: 'count' }],
      oranges: [{ $match: { type: 'orange' } }, { $count: 'count' }],
      bananas: [{ $match: { type: 'banana' } }, { $count: 'count' }]
    }
  }
])
What It Enables

It enables you to get multiple detailed summaries from the same data in one fast, organized step.

Real Life Example

A store manager wants to see how many apples, oranges, and bananas were sold today, along with the average price for each fruit type, all in one report without running separate queries.

Key Takeaways

Manual counting and sorting is slow and error-prone.

$facet runs multiple data pipelines at once on the same dataset.

This saves time and gives organized, detailed results in one query.