$unwind deconstructs arrays into one doc per element. $bucket histograms numeric values.
Unwind tags
db.products.aggregate([
{ $unwind: '$tags' },
{ $group: { _id: '$tags', count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])Practice: Run aggregation pipelines in mongosh.
Bucket prices
db.products.aggregate([
{ $bucket: {
groupBy: '$price',
boundaries: [0, 10, 25, 50, 100],
default: '100+',
output: { count: { $sum: 1 } }
}}
])
Important interview questions and answers
- Q: preserveNullAndEmptyArrays?
A: Keeps docs when array missing/empty after unwind. - Q: $facet?
A: Runs parallel sub-pipelines—dashboards in one round trip.
Self-check
- Use case for $unwind on tags?
- What does $bucket groupBy?
Tip: $unwind tag arrays before counting tag popularity.
Interview prep
- $bucket?
- Histograms numeric values into ranges.
- $facet?
- Runs parallel sub-pipelines in one command.