Open In App

How to Perform the SQL Join Equivalent in MongoDB?

In database management, with the rise of NoSQL databases like MongoDB, the approach to handling data relationships has evolved. MongoDB’s documentoriented nature and schemaless design provide a different perspective on joins compared to SQL.

In this article, we’ll learn about How to Perform the SQL Join Equivalent in MongoDB by understanding their types and performing various queries using Aggregation pipelines.



How to Perform the SQL Join Equivalent in MongoDB?

Let’s set up an Environment:

To understand How to perform the SQL Join equivalent in MongoDB we need a collection and some documents on which we will perform various operations and queries. Here we will consider two collections called Books and Authors which contain various information shown in the below images.



Books Collection

Authors Collection:

Authors Collection

Below Synax used for performing Joins

db.modelName.aggregate([
{
$lookup: {
from: "Collection to Join",
localField: "Field from the input documents",
foreignField: "Field from the documents of the 'from' collection",
as: "Pick a field-name as output"
}
}
]);

Explanation: This MongoDB aggregation syntax utilizes the $lookup stage to perform a left join between two collections.

Joins in MongoDB

1. Left Join

db.books.aggregate([
{
$lookup: {
from: "authors",
localField: "authorId",
foreignField: "_id",
as: "author"
}
}
]);

Output:

Left Join (Authors join to Books)

Explanation:

2. Right Join

db.authors.aggregate([
{
$lookup: {
from: "books",
localField: "bookId",
foreignField: "_id",
as: "book"
}
}
]);

Output:

Right Join (Books join to Authors)

Explanation:

3. Inner Join

db.books.aggregate([
{
$lookup: {
from: "authors",
localField: "authorId",
foreignField: "_id",
as: "author"
}
},
{
$match: {
"author": { $ne: [] }
}
}
]);

Output:

Inner Join (Authors join to Books)

Explanation:

4. Full Join

db.books.aggregate([
{
$lookup: {
from: "authors",
localField: "authorId",
foreignField: "_id",
as: "author"
}
},
{
$unionWith: {
coll: "authors",
pipeline: [
{
$lookup: {
from: "books",
localField: "bookId",
foreignField: "_id",
as: "book"
}
}
]
}
}
]);

Output:

Full Join (8 Documents)

Explanation:

Conclusion

Overall, MongoDB and SQL differ in their approach to data storage and querying, MongoDB provides powerful tools like aggregation pipelines and the $lookup operator to perform joins between collections. By understanding these concepts and applying them appropriately, you can effectively work with related data in MongoDB, providing flexibility and scalability to your database operations.


Article Tags :