NodeJS

    Optimize MongoDB Joins with $lookup for Faster Queries


    Introduction

    A system consisting of MySQL and PostgreSQL implements joins for efficient access to multiple table data. Since MongoDB operates as a NoSQL database it does not adopt traditional relational join standards. The `$lookup` aggregation stage functions as a left outer join mechanism for collections in MongoDB. The $lookup aggregation stage represents a significant functionality that proves advantageous when working with MongoDB databases that utilize normalization.

    Understanding `$lookup`

    Using the `$lookup` stage enables MongoDB users to conduct collections joins which fetches relationship data by avoiding multiple data request efforts. The feature becomes useful for situations that require cross-collection document references through shared fields.

    Syntax of `$lookup`

    { $lookup: { from: "<foreign_collection>", localField: "<local_field>", foreignField: "<foreign_field>", as: "<output_field>" }}

     

    The name of the collection to join appears here.

    The match occurs through the `localField` parameter containing the current collection object field.

    The matching field within the foreign collection exists under the name `localField`.

    Therefore the "as" parameter defines the name of output array field for storing matched documents.

    The following query shows the order of joining orders with users Collections

    Consider a collection of orders which contains user IDs that need user detail retrieval from the users collection through `$lookup`.

    Orders Collection

    { "_id": ObjectId("654321"), "orderId": "ORD12345", "userId": ObjectId("507f1f77bcf86cd799439011"), "amount": 250}

     

    users Collection

    { "_id": ObjectId("507f1f77bcf86cd799439011"), "name": "John Doe", "email": "johndoe@example.com"}

     

    The `$lookup` stage allows you to retrieve user information by linking orders collection data with user collection content.

    db.orders.aggregate([ { $lookup: { from: "users",  localField: "userId", foreignField: "_id",  as: "userDetails"  } }, { $unwind: "$userDetails" }]);

    Output

    { "_id": "654321", "orderId": "ORD12345", "userId": "507f1f77bcf86cd799439011", "amount": 250, "userDetails": { "_id": "507f1f77bcf86cd799439011", "name": "John Doe", "email": "johndoe@example.com" }}

     

    Ready to transform your business with our technology solutions?   Contact us today to Leverage Our Nodejs Expertise. 

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    NodeJS

    Related Center Of Excellence