While MongoDB itself doesn't support traditional joins like relational databases, you can achieve similar results using the Aggregation Framework. Here's how to perform joins between collections in Node.js with MongoDB:
Using $lookup:
The $lookup stage within the aggregation pipeline allows you to link documents from different collections based on a shared field. Here's a breakdown:
-
Define the Pipeline:
-
Create an aggregation pipeline using the
aggregate()method on your collection object. -
The pipeline is an array of stages that transform the data.
-
-
$lookup Stage:
-
Include a
$lookupstage within the pipeline. -
This stage specifies:
-
from: The name of the collection to join with. -
localField: The field in the current collection for the join. -
foreignField: The corresponding field in the foreign collection. -
as: The name to use for the joined data in the output.
-
-
Code Example (Inner Join):
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function joinCollections() {
try {
await client.connect();
const database = client.db("myDatabase");
const ordersCollection = database.collection("orders");
const pipeline = [
{
$lookup: {
from: "products", // Foreign collection
localField: "productId", // Field in orders collection
foreignField: "_id", // Field in products collection (often _id)
as: "productDetails" // Name for joined data
}
},
// ... (Optional additional stages for filtering or transformation)
];
const cursor = ordersCollection.aggregate(pipeline);
const results = await cursor.toArray();
console.log(results); // Array containing orders with joined product details
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
joinCollections();
Explanation:
-
This code joins the
orderscollection with theproductscollection. -
The
$lookupstage links documents where theproductIdinordersmatches the_idinproducts. -
The joined product details are stored in the
productDetailsarray within each order document.
Additional Considerations:
-
You can specify join types (inner, left outer, etc.) by adding the
letoperator and conditional expressions within the$lookupstage. -
For complex joins involving multiple collections, you can chain multiple
$lookupstages within the pipeline. -
Refer to the official MongoDB documentation for detailed explanations, examples, and advanced functionalities of the Aggregation Framework, including $lookup: https://www.mongodb.com/docs/manual/aggregation/
By leveraging the Aggregation Framework and the $lookup stage, you can effectively achieve data joins between collections in Node.js with MongoDB.