$set/$addFields, $replaceRoot, $merge, and window-like patterns with $setWindowFields (version-dependent).
addFields
db.orders.aggregate([
{ $addFields: { tax: { $multiply: ['$total', 0.2] } } },
{ $addFields: { grandTotal: { $add: ['$total', '$tax'] } } }
])Practice: Run aggregation pipelines in mongosh.
$merge to collection
db.orders.aggregate([
{ $match: { status: 'shipped' } },
{ $group: { _id: '$customerId', revenue: { $sum: '$total' } } },
{ $merge: { into: 'customer_revenue', on: '_id', whenMatched: 'replace', whenNotMatched: 'insert' } }
])Materializes analytics collection—document merge permissions in production.
Important interview questions and answers
- Q: $merge vs $out?
A: $out replaces target collection; $merge upserts with rules. - Q: $facet use?
A: Multiple reports in one aggregation command.
Self-check
- What does $addFields do?
- When use $merge?
Pitfall: $merge permissions—test on staging before materializing prod analytics.
Interview prep
- $merge?
- Writes pipeline output into collection with merge rules.
- $addFields?
- Adds computed fields without replacing doc.