Sure, here is a practical example of how to use the join()
operation in MongoDB:
Create two collections:
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017");
async function connectToMongo() {
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (err) {
console.error(err);
}
}
async function createCollections() {
try {
await connectToMongo();
const db = client.db("test");
const studentCollection = await db.createCollection("student");
const courseCollection = await db.createCollection("course");
// Insert some demo data into the collections
await studentCollection.insertMany([
{ name: "olee", roll: 23 },
{ name: "john", roll: 24 },
{ name: "doe", roll: 25 },
]);
await courseCollection.insertMany([
{ name: "Math", student_id: 23 },
{ name: "Science", student_id: 23 },
{ name: "English", student_id: 24 },
{ name: "History", student_id: 25 },
]);
client.close();
} catch (err) {
console.error(err);
}
}
createCollections();
Join the two collections:
async function joinCollections() {
try {
await connectToMongo();
const db = client.db("test");
const studentCollection = db.collection("student");
const courseCollection = db.collection("course");
// Join the two collections on the `student_id` field
const cursor = await studentCollection
.aggregate([
{
$lookup: {
from: courseCollection.collectionName,
localField: "_id",
foreignField: "student_id",
as: "courses",
},
},
])
.find({});
while (await cursor.hasNext()) {
const document = await cursor.next();
console.log("Document with joined data:");
console.log(document);
}
client.close();
} catch (err) {
console.error(err);
}
}
joinCollections();
Output:
Document with joined data: { _id: ObjectId(“653feeac8dac443c1b38e3f7”), name: ‘olee’, roll: 23, courses: [ { name: ‘Math’, student_id: 23 }, { name: ‘Science’, student_id: 23 } ] } Document with joined data: { _id: ObjectId(“653feeac8dac443c1b38e3f8”), name: ‘john’, roll: 24, courses: [ { name: ‘English’, student_id: 24 } ] } Document with joined data: { _id: ObjectId(“653feeac8dac443c1b38e3f9”), name: ‘doe’, roll: 25, courses: [ { name: ‘History’, student_id: 25 } ] }
This is just a basic example of how to use the join()
operation in MongoDB. You can use it to join multiple collections on multiple fields to create complex queries.