How to lookup in mongodb

Posted By : Himanshu sharma | 18-Dec-2016

Lookup in MongoDB

Before 3.2 mongodb join in mongodb is not possible . But now after mongodb join (left outer join is possible)

          db.college.aggregate([
   2:     {$match:{"college.name" : "Amrapali institude",
   3:              "college.Id" : "306"}},
   4:     {$lookup: {
   5:         from: "courses",
   6:         as: "courseData",
   7:         localField: "_id",
   8:         foreignField: "courses.collegeId"
   9:     }},
  10:     {$unwind: "$courseData"},
  11:     {$project:{"Title":1,
  12:                "courseName":"$customerData.courseName",
  13:                "duration" :"$customerData.courseTime"}},
  14: ])

what we are doing  here is we are all course whose colleageId and colleageName are 306 ans Amrapali institude respectively .THe result of join is each college contain array of its course so we use $unwind to to “flatten” them out .

 

NOTE: that for forgien key you should do "indexing" on it.

 

THANKS

About Author

Author Image
Himanshu sharma

Himanshu has marvelous coding skills. In Free time too he loves to do coding and sometimes play Cricket.

Request for Proposal

Name is required

Comment is required

Sending message..