Updated March 4, 2023
Introduction to JS MongoDB Join
Join us one of the biggest differences between NoSQL and SQL databases. Using a common field between them, the Join clause in SQL allows us to combine rows from tables of two or more. In this topic, we are going to learn about MongoDB Join.
It is not always that No JOIN = = No SQL.
MongoDB document-oriented databases are designed to store the denormalized data. There is a new lookup operation used as a $lookup introduced in MongoDB 3.2 version. This operation can perform left outer join-like operations on more than two collections. But, lookup operators are permissible in only aggregation operations.
The Syntax for JS MongoDB Join Aggregation
$lookup
Let us assume these are like the pipeline of operators that group, query, and filter a result. One operator output is used as the input of the next. The find queries are easier and simpler than that of aggregation level of difficulty. And these will in general run slower than usual. These are however powerful and an invaluable choice for complex operations of search.
Let us understand aggregation with the help of an example –
In this example let us think that we are creating a social media platform with a collection of users. It has the storage of all the details of the user in separate documents.
{
"_id": ObjectID("96945b421236f5c1883bdac7"),
"name": "User name,(first name and last name)",
"country": "India",
"dob": ("2000-05-18"),
"email: "[email protected]"
}
The number of necessary fields to be added is our wish. But in SQL or MongoDB, all those require a unique _id field containing a value unique to itself. In SQL this unique value or unique key is called the primary key. this will be inserted all by itself automatically if it is necessary. Now post collection is required by a social network that will help us Store the user data and numerous updates. Storage of text date and rating in the documents is done as a reference user_id ID field and the user who put it.
let us Create the same –
{
"_id": ObjectID("45b83bc76f5c1969cc1"),
"user_id": ObjectID("96945b421236f5c1883bdac7"),
"date: ("2020-07-16"),
"text": "Hey there, this is kavya. I am waiting for reply",
"rating": "first priority"
}
The aggregate query in MongoDB is passed as pipeline operators array which defines every operator in a particular order. Initially, the documents we need to be extracted from the collection of posts that contain the rating correctly using the filter match $match.
{ "$match":63.0
{
"rating": "first priority"
}
}
How is JS MongoDB Join Created?
Like for example, there are tables named publishers and books, one can write the commands in SQL like the following:
SELECT title.of.the.book, name.of.the.publisher
FROM the.book
LEFT JOIN the.book.id.num.publisher ON id.num.publisher
Here, the table of the.book has an id.num.pub field which is directed towards the id field in the table of the publisher.
In practical usage, this is very much possible because a single publisher can publish thousands of books at a time. Now if there is an optimization in the publisher details, we can do that too, by updating the publisher details or changing the records. Redundancy in the data is minimal due to no repetition in the information of publishers in every single book. This technique is called normalization.
A range of normalization is offered by SQL databases and features of constraints for ensuing relationship maintenance.
Example –
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection('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));
db.close();
});
});
Output:
Conclusion
Lookup is very powerful and useful all it requires is an aggregate query complexity in even the basic example. for more powerful clauses of join, it is not a substitute offered in SQL, neither the constraints are offered by MongoDB. Urban post documents will remain even if you’ll document is deleted. The operator lookup should be required infrequently. you are probably using the wrong data store if you need it a lot. Use the relational SQL database if you have relational data.
Recommended Articles
This is a guide to MongoDB Join. Here we discuss how is JS MongoDB Join created to understand aggregation with the help of an example. You may also have a look at the following articles to learn more –