EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Join Two Collections
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

MongoDB Join Two Collections

By Aanchal SharmaAanchal Sharma

MongoDB Join Two Collections

Definition on MongoDB Join Two Collections

MongoDB is a NoSQL database that is one of the most customary documents accessible and stores both as a completely controlled cloud service and also for deploying on self-managed infrastructure. Since MongoDB is not an RDBMS type, but still, a user can execute a left outer join by means of the $lookup stage. This stage $lookup allows you to state which collection a user needs to join with the present collection and also which fields that must match.

In MongoDB it is quite difficult to relate data from one collection to another excluding when basic script query functions are used. Therefore, to resolve this the JOIN concept is introduced which facilitates the data relation. MongoDB JOIN operation with two collections is performed by the use of $lookup operator developed having version 3.2.

Syntax:

The key concept behind the MongoDB JOIN operation is to achieve a correlation between one collection data to another one. This is done by using the $lookup operator so, the basic syntax for this to join two collections can be defined as follows:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

{
$lookup:
{
From:<join collections>,
localField: <input documents’ field>,
foreignField:<documents’ field of the ‘from’ collection>,
as: <result array field>
}
}

The $lookup operator proceeds a document having the below fields:

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,294 ratings)
  • From: It states the collection within the identical database for executing the join with but with Sharded Collection Restrictions.
  • LocalField: It states the field from the documents input to the stage of $lookup which operates an equivalence match on the local-field to the foreign field from the documents of the collection ‘from’. When an input document has no local-field value then this operator will give the field to have a null value for further matching purposes.
  • foreignField: It states the field from the documents in the ‘from’ collection which operates an equivalence match on the foreignField to the localField from the input documents. When a document in the collection ‘from’ has no value for the foreignField then this operator will give the field to have a null value for further matching purposes.
  • As: It states the name of the new array field for adding to the input documents. Also, the new array field includes the matching documents from the collection ‘from’. But when the stated name already prevails in the input document then the prevailing field will be overwritten.

In the case of the SQL concept, the result of a JOIN operation is always a different row that associates all fields present from the parent and foreign tables. But in MongoDB, the case is variant where the output documents are supplemented as an array of native collection documents.

How to join two collections in MongoDB?

For joining MongoDB collections, we require to implement the operator as $lookup, which is defined as a stage executing a left outer join with other collection and also aids to filter data info from joined documents.
Suppose a user needs to fetch all the students with grades, then the below query can be written:

Students.aggregate([{
$lookup: {
From: ‘Grades’,
LocalField: ‘Student_id’,
foreignField: ‘Stud_id’,
as: ‘Student_grade’
}}]);

We can see in the above query that the initial parameter named ‘from’ states the collection that is to be joined with the present one, on the other side the ‘localField’ parameter states the key prevailing in the present collection that is to be matched with the foreign key in another collection by means of ‘foreignField’ parameter. Here, Student_id from Students and stud_id from Grades are matched as well as joined for retrieving the data. Also, the end parameter ‘as’ is added as a code-named to the data.

It must be noted that here in every record of result from lookup, also the data from the joined table appears inside an array as the primary element, every one row from the output data of the query above that will display like,

{_ID: String, Quantity: Number, Student_id: String, Student_grade: Array, Stud_id: String, Student_name: String}

Here, in the grades array, the initial element will be the data that the query joined.

Example

Let us illustrate few examples to show the joining of two collections in MongoDB explained as follows:
Suppose we have two collections created named students and marks as,

Students:

{“_id”: 1, “name”: “Nikhil Singh”, “age”: 25, “grade”: “A”}
{“_id”: 2, “name”: “Kiran Sharma”, “age”:20, “grade”: “B”}
{“_id”: 3, “name”: “Krishna Raj”, “age”: 19, “grade”: “A”}
db.Students.find()

1

Marks:

{“_id”: 1, “English”: “A”, “Maths”: “B”, “Science”: “A”}
{“_id”: 2, “English”: “C”, “Maths”: “A”, “Science”: “B”}
{“_id”: 3, “English”: “B”, “Maths”: “C”, “Science”: “A”}
db.Grades.find()

2

We can fetch the students’ marks with corresponding grades by means of the $lookup operator using the JOIN methodology defined below:

Db.getCollection(‘Students’).aggregate([{
$lookup:
{
From: “Grades”,
localField: “_id”,
foreignField: “_id”,
as: “StudentMarks”
}
}])

On execution, the output will provide the following results,

{“_id”: 1, “name”: “Nikhil Singh”, “age”: 25, “grade”: “A”, “StudentMarks”: [{“_id”: 1, “English”: “A”, “Maths”: “B”, “Science”: “A”}]}

3

The structure of the written query may decide the performance duration. Like for instance, when there are several documents in one collection over the other, then aggregation is needed from one collection with smaller documents followed by lookup in the one having various documents. This type of lookup performed for the selected field from the smaller documents collection is rather finest and proceeds smaller time than executing numerous lookups for a selected field present in the collection having various documents. Thus, it is sensible to place the smaller collection initially.

But the order of the databases does not trouble in case of a relational database as maximum of the SQL interpreters includes optimizers that provide access to additional information to select which one must be the primary one.

In this MongoDB, to simplify the JOIN operation we may require to implement an index. Since all MongoDB documents include an _id key that for a relational DBM is measured as the primary key. An index delivers a better chance of minimizing the quantity of data which requires to be retrieved besides associating the operation when applied in the $lookup foreign key.

Conclusion

JOIN operator is one of the basic distinctive features available between SQL database and NoSQL database. In SQL databases, a user can execute a JOIN operation between two tables inside identical or different databases.

While the case in MongoDB for JOIN is varied, MongoDB lets JOIN operations perform between two collections implemented in a similar database.

Recommended Articles

This is a guide to MongoDB Join Two Collections. Here we discuss definition, How to join two collections in MongoDB? along with examples respectively. You may also have a look at the following articles to learn more –

  1. MongoDB Join
  2. MongoDB group by
  3. MongoDB Import
  4. MongoDB Sharding
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (14 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more