Intermediate LevelMongoDB & Mongoose
How does the $merge aggregation stage create updateable Materialized Views?
❓ Interview Prompt: Explain $merge stage, writing aggregation results to output collections, on-match behavior (replace, merge, keepExisting), and Materialized Views.
The '$merge' aggregation stage writes pipeline results into an output collection, enabling the creation of updateable Materialized Views:
Features:
•
Atomically updates existing matching documents or inserts new documents.
•
Allows incremental updates to pre-computed analytical report collections!
Code Implementation Example
typescript
import { OrderModel } from './models/Order';
async function updateDailySalesMaterializedView() {
await OrderModel.aggregate([
{ $match: { status: 'COMPLETED' } },
{
$group: {
_id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
totalSales: { $sum: '$totalAmount' }
}
},
{
$merge: {
into: 'daily_sales_summary',
whenMatched: 'replace',
whenNotMatched: 'insert'
}
}
]);
}💡Creating an updateable Materialized View using the $merge aggregation stage.
🎯 Interview Key Takeaway
Use $merge to store aggregation outputs in target collections as high-performance Materialized Views.
#$merge#Materialized Views#Aggregation#Intermediate
Back to all MongoDB & Mongoose Questions→