Introduction
In this blog, let's discuss how to join two collections using the $lookup function in MongoDB.
Background
We already know how to use joins in SQL Server but MongoDB is document based and there is no syntax for joins in MongoDB. Most of the time we require a join between more than one table. However, it provides $lookup a aggregation function that works like join.
Below, I have created a demostration example.
We have two collections- Customer and Citymaster.
-
-
- db.getCollection('Customer').find({})
-
-
- db.getCollection('CityMaster').find({})
Now, we use the $lookup aggregation function.
- db.Customer.aggregate([
-
- {$lookup: {from: "CityMaster", localField: "CityId", foreignField: "id", as: "CityDetail"}},
- {$match: {details: {$ne: []}}}
- ]);
Output:
- {
- "_id" : ObjectId("598d4dd16abd19bbecbac78b"),
- "name" : "Puneet",
- "address" : "Samarth Nagar",
- "CityId" : 1,
- "CityDetail" : [
- {
- "_id" : ObjectId("598d4d4f6abd19bbecbac779"),
- "id" : 1,
- "cityname" : "Gwalior"
- }
- ]
- }
-
-
- {
- "_id" : ObjectId("598d4dec6abd19bbecbac78d"),
- "name" : "Raj",
- "address" : "DD Nagar",
- "CityId" : 2,
- "CityDetail" : [
- {
- "_id" : ObjectId("598d4d696abd19bbecbac77f"),
- "id" : 2,
- "cityname" : "Bhopal"
- }
- ]
- }
-
-
- {
- "_id" : ObjectId("598d4e0b6abd19bbecbac791"),
- "name" : "Jhon",
- "address" : "MP Nagar",
- "CityId" : 2,
- "CityDetail" : [
- {
- "_id" : ObjectId("598d4d696abd19bbecbac77f"),
- "id" : 2,
- "cityname" : "Bhopal"
- }
- ]
- }
-
-
- {
- "_id" : ObjectId("598d4e216abd19bbecbac795"),
- "name" : "Ankit",
- "address" : "Samarth Nagar",
- "CityId" : 1,
- "CityDetail" : [
- {
- "_id" : ObjectId("598d4d4f6abd19bbecbac779"),
- "id" : 1,
- "cityname" : "Gwalior"
- }
- ]
- }
Summary
I hope you understood how to use the $lookup function in MongoDB.