Joins in MongoDB

Joins in MongoDB is introduced in MongoDB 3.2 with $lookup aggregate. Compared to SQL server it is Equivalent to Left outer Equi join. Such that repeated data can be avoided. Update seems to be simple.

$lookup Example with MongoDB:

see the two collections below with names Student and Address


                    Student
                  Address

{
"_id":"654j56df0e8e9fdfg",
"First Name":"Rakesh",
"Second Name":"balan",
"Postalcode":"600047"
}


{
"_id":"979475jh34f34",
"PstlCode":"600047",
"address":[{
"City":"Chennai",
"Area":"T.Nagar",
"Landmark":"Near canara Bank",
"House No":"52-5"
}]
}


Query to fetch data using $lookup

db.Student.aggregate([
{ $match : {
_id: “654j56df0e8e9fdfg”
},
{$lookup: {
from: “Address”,
localField:”Postalcode”,
foreignField:”PstlCode”,
as : “Student_address”
}
  }
])


Output for the above Query looks like:


{
     "_id": "654j56df0e8e9fdfg",
     "First Name": "Rakesh",
     "Second Name": "balan",
     "Postalcode": "600047",
     "Student_address": [{
          "_id": "979475jh34f34",
          " PstlCode ": "600047",
          "address": [{
              "City": "Chennai",
              "Area": "T.Nagar",
              "Landmark": "Near canara Bank",
              "House No": "52-5"
          }]
     }]

}