What if you could get many answers from your data in one simple step, without extra work or mistakes?
Why $facet for multiple pipelines in MongoDB? - Purpose & Use Cases
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.
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 $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.
db.fruits.find({ type: 'apple' }).count()
db.fruits.find({ type: 'orange' }).count()
db.fruits.find({ type: 'banana' }).count()db.fruits.aggregate([
{ $facet: {
apples: [{ $match: { type: 'apple' } }, { $count: 'count' }],
oranges: [{ $match: { type: 'orange' } }, { $count: 'count' }],
bananas: [{ $match: { type: 'banana' } }, { $count: 'count' }]
}
}
])It enables you to get multiple detailed summaries from the same data in one fast, organized step.
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.
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.