🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Node.js Notes
Topic #70

MongoDB Join


Join Collections

MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage.

The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.

Consider you have a "orders" collection and a "products" collection:

orders

[
  { _id: 1, product_id:
154, status: 1 }
]

products

[
  { _id: 154, name:
'Chocolate Heaven' },
  { _id: 155, name: 'Tasty Lemons' },
  {
_id: 156, name: 'Vanilla Dreams' }
]

Example

let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

let dbo = db.db("mydb");

dbo.collection('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));

db.close();
  });
});

Save the code above in a file called "demo_mongodb_join.js" and run the file:

C:\Users\Your Name>node demo_mongodb_join.js

Which will give you this result:

[
  { "_id": 1, "product_id":
154, "status": 1, "orderdetails": [
    { "_id": 154, "name":
"Chocolate Heaven" } ]
  }
]

As you can see from the result above, the matching document from the products collection is included in the orders collection as an array.

Want to go beyond the notes?

Join CodingNow 2.0's Node.js course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

MongoDB Join – FAQs

Quick answers about learning MongoDB Join in Node.js.

This free note from CodingNow 2.0 explains MongoDB Join in Node.js — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Node.js topic on CodingNow 2.0, including MongoDB Join, is 100% free with no signup required.
With focused practice, most students grasp MongoDB Join in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now