ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Mongodb Join in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1409' AND `tutorial_status`=1 LIMIT 1

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:

  1. βœ… Native MongoDB Driver

  2. πŸͺ„ Mongoose (with populate)

Let’s see both πŸ‘‡


βœ… 1. Using Native MongoDB Driver with $lookup

🧱 Sample Collections

users

json

{ _id: 1, name: "Alice", city_id: 101 }

cities

json

{ _id: 101, name: "New York" }


πŸ“¦ Step 1: Install MongoDB

bash

npm install mongodb


πŸ”— Step 2: Use $lookup to Join

js

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

bash

npm install mongoose


πŸ”— Step 2: Define Schemas and Join

js

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

FeatureMongoDB Native DriverMongoose
Join support$lookup in aggregation.populate() on ref fields
Easy to useMedium (but powerful)Super easy
OutputManual control of structureAuto maps references

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql