Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to drop collection in MongoDb using Node.js ?
Next article icon

How To Get Data From 2 Different Collections Of MongoDB Using Node.js?

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To retrieve data from two different collections in MongoDB using Node.js, we typically use the Mongoose library or the native MongoDB driver to establish a connection, query both collections and then combine or process the data as needed. This approach allows you to query multiple collections in parallel or in sequence, depending on your application’s requirements.

To get data from a collection with Mongoose in NodeJS you have to have two necessary things:

  1. Schema: It is a document structure that contains the property with its types (default value, validations, etc. when required) as a key-value pair.
  2. Model: It is a class created with the help of defined Schema and a MongoDB document is an instance of Model. Therefore, it acts as an interface for the MongoDB database for creating, reading, updating, and deleting a document.

After having a model, we can use the method find() on the model of a particular collection to get documents of the collection.

Syntax: 

<Model_Name>.find(<query>,<projection>)
  • <query>: It is optional. It specifies a selection filter that is used to filter documents using various MongoDB query operators. If not passed, all the documents are returned.
  • <projection>: It is optional. It contains fields that we want to be returned to the documents that match the query filter. If not passed, all the fields are returned.

Steps To Get Data From 2 Different Collections Of MongoDB

Step 1: You can visit the link Install mongoose to install the Mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Now you can import the Mongoose module in your file using:

const mongoose = require('mongoose');

Step 3: Create a folder and add model.js and main.js files into it.

  • model.js: It contains schemas and models for all the collections you want to use, and then we are exporting all the models created so that they can be imported into the file in which we will get data from different collections.
  • main.js: It is the main server file here we will get data from two different collections.
JavaScript
//model.js  // Requiring module const mongoose = require('mongoose');  // Course Modal Schema const courseSchema = new mongoose.Schema({     _id: Number,     name: String,     category: String });  // Student Modal Schema const studentSchema = new mongoose.Schema({     name: String,     enroll: Number,     courseId: Number });  // Creating model objects const Course = mongoose.model('course', courseSchema); const Student = mongoose.model('student', studentSchema);  // Exporting our model objects module.exports = {     Student, Course } 

Database: We already have documents in our Courses and Students collections from which we are going to get data as shown below:

mongoose-model
Get Data From 2 Different Collections Of MongoDB Using Node.js

Step 4: Database connection can be easily established using mongoose like:

mongoose.connect('mongodb://localhost:27017/GFG',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});

Step 5: Write down the following code in the main.js file.

JavaScript
//main.js  const mongoose = require('mongoose');  // Importing Models Student and Course from model.js const { Student, Course } = require('./model');  // Connecting to database mongoose.connect('mongodb://localhost:27017/GFG',     {         useNewUrlParser: true,         useUnifiedTopology: true,         useFindAndModify: false     });  var dbcourse = [];  // Finding courses of category Database Course.find({ category: "Database" })     .then(data => {         console.log("Database Courses:")         console.log(data);          // Putting all course id's in dbcourse array         data.map((d, k) => {             dbcourse.push(d._id);         })          Student.find({ courseId: { $in: dbcourse } })             .then(data => {                 console.log("Students in Database Courses:")                 console.log(data);             })             .catch(error => {                 console.log(error);             })     })     .catch(error => {         console.log(error);     }) 


Run main.js file using the below command:

node main.js

Explanation: In the above code, in the file main.js, we are getting all the documents of Course collection whose category is Database then storing _id of each course in dbcourse array then getting all the documents from the Student collection whose is enrolled in any course of category Database.

Output: We are getting data from two different collections Courses and Students in the console shown below:

data-from-different-collection
Get Data From 2 Different Collections Of MongoDB Using Node.js

Next Article
How to drop collection in MongoDb using Node.js ?

L

localhost3000
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-Methods
  • Mongoose
  • NodeJS-Questions

Similar Reads

  • How to Delete a Document From MongoDB Collection using NodeJS?
    MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. This means that MongoDB isn’t based on a table-like relational database structure but provides an altogether different mechanism for data storage and retrieval. This stora
    4 min read
  • How to Get Data from MongoDB using Node.js?
    One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
    6 min read
  • How to get Distinct Documents from MongoDB using Node.js ?
    MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational.  MongoDB module: This module of Node.js is used for connecting the Mongo
    2 min read
  • How to drop collection in MongoDb using Node.js ?
    MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
    2 min read
  • How to Join Two Collections in Mongodb using Node.js ?
    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 CollectionsIn MongoDB, a collection is a group
    4 min read
  • How to sort collection of MongoDB Database in descending order using Node.js ?
    MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
    2 min read
  • How to create new Collection in MongoDB using Node.js ?
    MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
    2 min read
  • How to Insert a Document into a MongoDB Collection using Node.js?
    MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guid
    5 min read
  • How to Connect to a MongoDB Database Using Node.js
    MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
    4 min read
  • How to Connect to a MongoDB Database Using the Node.js Driver ?
    MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON). In this article, we connect the MongoDB database to your b
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences