QA
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→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?