Aggregation Pipeline
Give a real production-style example of using Aggregation Pipeline. Walk through the scenario end-to-end.
Answers use simple, clear English.
Audio N/AQuick interview answer
Scenario: Monthly revenue by category: $match date range, $unwind items, $group by category sum price. Implementation notes: Index fields in initial $match; $project early to trim fields.
Detailed answer
Scenario: Monthly revenue by category: $match date range, $unwind items, $group by category sum price. Implementation notes: Index fields in initial $match; $project early to trim fields. Core: Stages: $match → $group → $sort → $lookup (join) → $project. Pipeline runs server-side; push filters early in $match for index use. Real-time example: Monthly revenue by category: $match date range, $unwind items, $group by category sum price. Pros: Powerful analytics in database; reduces app-side processing. Cons: $lookup expensive on large collections without indexes; memory limits on sort/group. Common mistakes: $lookup before $match blowing working set; missing allowDiskUse on huge sorts. Best practices: Index fields in initial $match; $project early to trim fields. Audience level: Tech Lead.
Full explanation
Stages: $match → $group → $sort → $lookup (join) → $project. Pipeline runs server-side; push filters early in $match for index use.
Real example & use case
Monthly revenue by category: $match date range, $unwind items, $group by category sum price.
Pros & cons
Pros: Powerful analytics in database; reduces app-side processing. Cons: $lookup expensive on large collections without indexes; memory limits on sort/group.
Common mistakes
$lookup before $match blowing working set; missing allowDiskUse on huge sorts.
Best practices
Index fields in initial $match; $project early to trim fields.
Follow-up questions
Open one as its own read / solve / listen card