While MongoDB is a document database, relational data joins across multiple collections can be performed using Aggregation Pipelines and the $lookup stage operator.
flowchart TD
subgraph ORDERS ["orders collection"]
O1["{ _id: 1, customerId: ObjectId('...'), total: 299.99 }"]
end
subgraph USERS ["users collection"]
U1["{ _id: ObjectId('...'), name: 'Alice', email: '[email protected]' }"]
end
ORDERS -->|"$lookup: from 'users', localField 'customerId', foreignField '_id'"| JOINED["Aggregation Result Document"]
import { MongoClient } from 'mongodb';
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function executeLookupAggregationJoin() {
try {
await client.connect();
const db = client.db('kodersolution_no_sql');
const orders = db.collection('orders');
// Aggregation Pipeline with $lookup and $unwind
const pipeline = [
{
$lookup: {
from: 'users', // Target collection to join
localField: 'customerId', // Field in orders collection
foreignField: '_id', // Field in users collection
as: 'customerDetails' // Output array field name
}
},
{
$unwind: '$customerDetails' // Flatten customerDetails array to object
},
{
$project: {
_id: 1,
orderTotal: '$totalAmount',
customerName: '$customerDetails.name',
customerEmail: '$customerDetails.email'
}
}
];
const aggregatedResults = await orders.aggregate(pipeline).toArray();
console.log('Joined Aggregation Results:');
console.log(aggregatedResults);
} catch (err) {
console.error('MongoDB $lookup Aggregation Error:', err.message);
} finally {
await client.close();
}
}
executeLookupAggregationJoin();
foreignField (e.g. users._id) have indexes to optimize $lookup performance.$unwind: Use $unwind: '$arrayField' after $lookup to convert the single-match array returned by $lookup into an embedded object.$match: Place $match stages at the very beginning of the pipeline to reduce the number of documents passed to $lookup.What is the purpose of the $unwind stage in a MongoDB aggregation pipeline following a $lookup join?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With