Intermediate LevelMongoDB & Mongoose
How do custom pipeline joins work inside the $lookup stage?
❓ Interview Prompt: Explain advanced $lookup syntax (let variables, custom sub-pipeline array), joining with condition filtering, and projection.
Beyond simple equality joins, the '$lookup' stage supports a custom 'pipeline' array that executes arbitrary sub-pipeline transformations on target joined collections before merging results:
Features:
•
Define variables via 'let: { orderUserId: "$userId" }'.
•
Filter, project, and sort joined documents inside '$match' using '$expr'.
Code Implementation Example
typescript
import { UserModel } from './models/User';
async function getUsersWithRecentCompletedOrders() {
const results = await UserModel.aggregate([
{
$lookup: {
from: 'orders',
let: { userId: '$_id' },
pipeline: [
{
$match: {
$expr: { $eq: ['$userId', '$$userId'] },
status: 'COMPLETED'
}
},
{ $sort: { createdAt: -1 } },
{ $limit: 3 }
],
as: 'recentOrders'
}
}
]);
return results;
}💡Executing advanced $lookup joins with custom sub-pipelines.
🎯 Interview Key Takeaway
Use $lookup with custom pipelines to filter and limit joined subdocuments before merging.
#$lookup#Pipeline Joins#Aggregation#Intermediate
Back to all MongoDB & Mongoose Questions→