Articles → MONGODB → $Lookup Operator In Mongodb

$Lookup Operator In Mongodb






Purpose





Syntax


db.collection.aggregate([
   {
      $lookup:
         {
           from: <collection to join>,
           localField: <field from the input documents>,
           foreignField: <field from the documents of the "from" collection>,
           as: <output array field>
         }
   }
])




ParameterExplanation
fromspecifies the collection to join with
localFieldspecifies the field from the input document to match the foreign key in the from collection
foreignFieldspecifies the field of the from collection to match with the localField
asspecifies the name the output array



Collections




Picture showing the Articles Collection in MongoDB
Click to Enlarge

Picture showing the ArticlesComments Collection in MongoDB
Click to Enlarge


$Lookup Operator


db.Articles.aggregate([
  {
    $lookup: {
      from: "ArticlesComments",
      localField: "_id",
      foreignField: "_subjectid",
      as: "ArticleDetails"
    }
  }
]);



Output


Picture showing the output of Lookup Operator In Mongodb
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, May 5, 2023
 
Updated On  -  Friday, October 13, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250