Intermediate LevelMongoDB & Mongoose
How does the $facet aggregation stage execute parallel sub-pipelines?
❓ Interview Prompt: Explain $facet stage, parallel aggregation pipelines on identical input documents, multi-category faceted search, and pagination summaries.
The '$facet' aggregation stage allows executing multiple aggregation pipelines concurrently on the same input document set:
Primary Use Case:
Executing multi-attribute product search filters, price range histograms, and paginated results with total counts in a single database query!
Code Implementation Example
typescript
import { ProductModel } from './models/Product';
async function getFacetedSearchResult(category: string) {
const results = await ProductModel.aggregate([
{ $match: { category } },
{
$facet: {
paginatedResults: [{ $skip: 0 }, { $limit: 10 }],
totalCount: [{ $count: 'count' }],
priceStats: [
{ $group: { _id: null, avgPrice: { $avg: '$price' }, maxPrice: { $max: '$price' } } }
]
}
}
]);
return results[0];
}💡Executing faceted product search using the $facet aggregation stage.
🎯 Interview Key Takeaway
Use $facet to run parallel analytical sub-pipelines and pagination metrics in a single database query.
#$facet#Aggregation#Faceted Search#Intermediate
Back to all MongoDB & Mongoose Questions→