[MONGOOSE] Example Aggregation with Optimizations - fourslickz/notes GitHub Wiki
Model.aggregate([
{ $match: { isActive: true } }, // Early match stage
{
$lookup: {
from: 'foreignCollection',
let: { foreignKey: '$foreignKey' },
pipeline: [
{ $match: { $expr: { $eq: ['$_id', '$$foreignKey'] } } },
{ $project: { field1: 1, field2: 1 } } // Limit returned fields
],
as: 'joinedData'
}
},
{ $project: { name: 1, joinedData: 1 } }, // Limit fields in the final result
{ $limit: 1000 } // Example of batch processing
])