
Mongodb Join in NodeJs
Joining collections in MongoDB is done using the $lookup
aggregation stage β think of it like a SQL JOIN. You can use it in Node.js with either:
β Native MongoDB Driver
πͺ Mongoose (with
populate
)
Letβs see both π
β
1. Using Native MongoDB Driver with $lookup
π§± Sample Collections
users
{ _id: 1, name: "Alice", city_id: 101 }
cities
{ _id: 101, name: "New York" }
π¦ Step 1: Install MongoDB
npm install mongodb
π Step 2: Use $lookup
to Join
const { MongoClient } = require('mongodb');const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);async function joinCollections() { try { await client.connect(); const db = client.db('myDatabase'); const result = await db.collection('users').aggregate([ { $lookup: { from: 'cities', // Collection to join localField: 'city_id', // Field in users foreignField: '_id', // Field in cities as: 'city_info' // Output array field } } ]).toArray(); console.log(JSON.stringify(result, null, 2)); } finally { await client.close(); }}joinCollections();
πͺ 2. Using Mongoose with populate()
Mongoose makes joins easy using ref + populate.
π¦ Step 1: Install Mongoose
npm install mongoose
π Step 2: Define Schemas and Join
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('Connected!'));// Define City schemaconst citySchema = new mongoose.Schema({ name: String });const City = mongoose.model('City', citySchema);// Define User schema with a referenceconst userSchema = new mongoose.Schema({ name: String, city: { type: mongoose.Schema.Types.ObjectId, ref: 'City' }});const User = mongoose.model('User', userSchema);// Join using populateasync function showJoinedData() { const users = await User.find().populate('city'); console.log(users); mongoose.disconnect();}showJoinedData();
β Summary
Feature | MongoDB Native Driver | Mongoose |
---|---|---|
Join support | $lookup in aggregation | .populate() on ref fields |
Easy to use | Medium (but powerful) | Super easy |
Output | Manual control of structure | Auto maps references |