MongoDB Query

Joining collections in MongoDB when working with Node.js allows you to query and combine data from multiple collections, similar to how JOIN operations work in SQL databases. In MongoDB, this is achieved using the $lookup aggregation stage. This powerful feature enables you to merge documents from two collections into a single document, providing a more relational view of your data. Below, we’ll explore how to perform joins between orders and products collections, and provide a practical example to help you grasp the concept.

Understanding $lookup

The $lookup stage in MongoDB’s aggregation framework allows you to specify which collection you want to join with the current collection. The basic syntax looks like this:

{
  $lookup:
     {
       from: "collectionToJoin",
       localField: "fieldNameInCurrentCollection",
       foreignField: "fieldNameInJoinedCollection",
       as: "outputArrayName"
     }
}
  • from specifies the name of the collection you want to join with.
  • localField is the field name in the current collection that will be matched against foreignField in the joined collection.
  • foreignField is the field name in the joined collection that corresponds to localField in the current collection.
  • as defines the name of the array field in the output document that will contain the joined information.

Join Collections Example: orders and products

Let’s consider a scenario where you have two collections: orders and products. Each order document contains a productId field that references a product in the products collection.

Collections Structure

  • Orders Collection:
{
  "_id": ObjectId("..."),
  "orderNumber": "12345",
  "productId": "abc123",
  "quantity": 2
}
  • Products Collection:
{
  "_id": "abc123",
  "name": "Laptop",
  "price": 999.99
}

Example: Joining orders with products

To join these collections, you want to match orders.productId with _id in products and add the product details to each order document.

Here’s how you can achieve this using Node.js and MongoDB:

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const dbName = 'yourDatabaseName'; // Replace with your actual database name

MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;

  const db = client.db(dbName);
  db.collection('orders').aggregate([
    {
      $lookup:
         {
           from: "products", // collection to join
           localField: "productId", // field from the orders collection
           foreignField: "_id", // field from the products collection
           as: "productDetails" // array field added to each order
         }
    }
  ]).toArray((err, res) => {
    if (err) throw err;
    console.log(JSON.stringify(res));
    client.close();
  });
});

In this example, for each document in the orders collection, MongoDB looks for matching documents in the products collection based on the productId. It then adds an array called productDetails to each orders document, which contains the matching products documents.

This approach allows you to retrieve related information from multiple collections using a single query, making your data retrieval more efficient and your application code simpler and cleaner.

Conclusion

Understanding how to join collections using MongoDB’s $lookup operation in Node.js is crucial for developing applications that require data from multiple collections. It enables you to perform more complex queries and data transformations, providing a powerful tool for handling relational data in a NoSQL database like MongoDB. As you’ve seen in the example above, implementing a join operation between orders and products is straightforward, yet it can significantly enhance your application’s capabilities.