How to Join Two Collections in Mongodb using Node.js ?

Joining two collections in MongoDB using Node.js can be accomplished using the aggregation framework. The $lookup stage in the aggregation pipeline allows you to perform a left outer join to another collection in the same database.

Understanding MongoDB Collections

In MongoDB, a collection is a group of documents that are stored together within the database. Collections are analogous to tables in relational databases but are schema-less, meaning each document within a collection can have a different structure.

Performing Joins in MongoDB

MongoDB is a non-relational database, which means it does not support traditional SQL joins like relational databases. However, MongoDB provides a way to perform similar operations using the $lookup aggregation stage.

Using $lookup in MongoDB

The $lookup stage in MongoDB’s aggregation framework allows you to perform a left outer join between two collections. It lets you specify the source collection, local field, foreign field, and output field to store the results of the join.

The below example joins the “orders” collection with the “products” collection based on the product_id field in the “orders” collection and the _id field in the “products” collection.

db.orders.aggregate([
{
$lookup: {
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'orderdetails'
}
}
]).toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
});

Step-by-Step Guide: Joining Collections with Node.js

To perform a collection join in MongoDB using Node.js, follow these steps:

Step 1: Create a NodeJS Application using the below command:

npm init - y

Step 2: Connect to MongoDB

Use the mongodb npm package to establish a connection to your MongoDB database.

Step 3: Perform the $lookup

Operation Use the aggregate method on your collection to perform the $lookup operation with the desired parameters.

Step 4: Handle the Result

Process the result of the join operation as needed within your Node.js application.

Example: Here’s an example of joining “orders” with “customers” collections using $lookup:

JavaScript
// performJoin.js
const { MongoClient } = require("mongodb");

// Connection URI
const uri = "mongodb://localhost:27017";

// Database Name
const dbName = "mydatabase";

async function performCollectionJoin() {
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        // Connect to MongoDB
        await client.connect();

        // Get reference to the database
        const db = client.db(dbName);

        // Perform $lookup aggregation to join orders with products
        const result = await db
            .collection("orders")
            .aggregate([
                {
                    $lookup: {
                        from: "products",
                        localField: "product_id",
                        foreignField: "_id",
                        as: "orderdetails",
                    },
                },
            ])
            .toArray();

        console.log(result);
    } catch (error) {
        console.error("Error performing collection join:", error);
    } finally {
        // Close the MongoDB connection
        await client.close();
    }
}

// Call the function to perform collection join
performCollectionJoin();
JavaScript
// insertData.js
const { MongoClient } = require("mongodb");

// Connection URI
const uri = "mongodb://localhost:27017";

// Database Name
const dbName = "mydatabase";

// Sample data for orders collection
const orders = [
    { _id: 1, product_id: 101, quantity: 2 },
    { _id: 2, product_id: 102, quantity: 1 },
    { _id: 3, product_id: 103, quantity: 3 },
];

// Sample data for products collection
const products = [
    { _id: 101, name: "Product A", price: 20 },
    { _id: 102, name: "Product B", price: 30 },
    { _id: 103, name: "Product C", price: 25 },
];

async function createDatabaseAndInsertData() {
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        // Connect to MongoDB
        await client.connect();

        // Get reference to the database
        const db = client.db(dbName);

        // Create orders collection and insert sample data
        const ordersCollection = db.collection("orders");
        await ordersCollection.insertMany(orders);

        // Create products collection and insert sample data
        const productsCollection = db.collection("products");
        await productsCollection.insertMany(products);

        console.log("Sample data inserted successfully.");
    } catch (error) {
        console.error("Error inserting sample data:", error);
    } finally {
        // Close the MongoDB connection
        await client.close();
    }
}

// Call the function to create database and insert sample data
createDatabaseAndInsertData();

Output:

output

Join Collections in MongoDB – FAQs

What is a left outer join in MongoDB?

A left outer join in MongoDB retrieves all documents from the left collection (from) and matches them with corresponding documents from the right collection (localField and foreignField).

How does the $lookup operator work?

The $lookup operator performs a left outer join between two collections in MongoDB based on specified fields (localField and foreignField).

Can you perform multiple joins in MongoDB?

Yes, MongoDB allows you to chain multiple $lookup stages to perform multiple joins between collections.

What are the advantages of using $lookup for joins?

The $lookup operator in MongoDB provides flexibility for performing joins on unstructured data without requiring a predefined schema.

How to handle large datasets when performing joins in MongoDB?

MongoDB supports various optimization techniques such as indexing and sharding to handle large datasets efficiently during join operations.



Contact Us