How to Join Two Collections in Mongodb using Node.js ?
Last Updated :
20 May, 2024
Joining two collections in MongoDB using Node.js can be accomplished using the aggregation framework. The $lookup
stage in the aggregation pipeline allows you to perform a left outer join to another collection in the same database.
Understanding MongoDB Collections
In MongoDB, a collection is a group of documents that are stored together within the database. Collections are analogous to tables in relational databases but are schema-less, meaning each document within a collection can have a different structure.
Performing Joins in MongoDB
MongoDB is a non-relational database, which means it does not support traditional SQL joins like relational databases. However, MongoDB provides a way to perform similar operations using the $lookup aggregation stage.
Using $lookup in MongoDB
The $lookup stage in MongoDB's aggregation framework allows you to perform a left outer join between two collections. It lets you specify the source collection, local field, foreign field, and output field to store the results of the join.
The below example joins the "orders" collection with the "products" collection based on the product_id field in the "orders" collection and the _id field in the "products" collection.
db.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));
});
Step-by-Step Guide: Joining Collections with Node.js
To perform a collection join in MongoDB using Node.js, follow these steps:
Step 1: Create a NodeJS Application using the below command:
npm init - y
Step 2: Connect to MongoDB
Use the mongodb npm package to establish a connection to your MongoDB database.
Step 3: Perform the $lookup
Operation Use the aggregate method on your collection to perform the $lookup operation with the desired parameters.
Step 4: Handle the Result
Process the result of the join operation as needed within your Node.js application.
Example: Here's an example of joining "orders" with "customers" collections using $lookup:
JavaScript
// performJoin.js
const { MongoClient } = require("mongodb");
// Connection URI
const uri = "mongodb://localhost:27017";
// Database Name
const dbName = "mydatabase";
async function performCollectionJoin() {
const client = new MongoClient(uri, { useUnifiedTopology: true });
try {
// Connect to MongoDB
await client.connect();
// Get reference to the database
const db = client.db(dbName);
// Perform $lookup aggregation to join orders with products
const result = await db
.collection("orders")
.aggregate([
{
$lookup: {
from: "products",
localField: "product_id",
foreignField: "_id",
as: "orderdetails",
},
},
])
.toArray();
console.log(result);
} catch (error) {
console.error("Error performing collection join:", error);
} finally {
// Close the MongoDB connection
await client.close();
}
}
// Call the function to perform collection join
performCollectionJoin();
JavaScript
// insertData.js
const { MongoClient } = require("mongodb");
// Connection URI
const uri = "mongodb://localhost:27017";
// Database Name
const dbName = "mydatabase";
// Sample data for orders collection
const orders = [
{ _id: 1, product_id: 101, quantity: 2 },
{ _id: 2, product_id: 102, quantity: 1 },
{ _id: 3, product_id: 103, quantity: 3 },
];
// Sample data for products collection
const products = [
{ _id: 101, name: "Product A", price: 20 },
{ _id: 102, name: "Product B", price: 30 },
{ _id: 103, name: "Product C", price: 25 },
];
async function createDatabaseAndInsertData() {
const client = new MongoClient(uri, { useUnifiedTopology: true });
try {
// Connect to MongoDB
await client.connect();
// Get reference to the database
const db = client.db(dbName);
// Create orders collection and insert sample data
const ordersCollection = db.collection("orders");
await ordersCollection.insertMany(orders);
// Create products collection and insert sample data
const productsCollection = db.collection("products");
await productsCollection.insertMany(products);
console.log("Sample data inserted successfully.");
} catch (error) {
console.error("Error inserting sample data:", error);
} finally {
// Close the MongoDB connection
await client.close();
}
}
// Call the function to create database and insert sample data
createDatabaseAndInsertData();
Output:
output
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read