Matching documents in the same collection by a reference

Hi, assuming i have the following document design:

{
 _id: ObjectID
  parent: ObjectID
}

Where parent property references to an existing _id property of another document in the same collection.
Is it possible to obtain both documents (the child and the parent document) with a single query operation?

I forget to say that the only thing we know is the _id property of the child

Hi @Matteo_Tarantino ,

You can perform a self $lookup to the same collection:

db.collection.aggregate( [
   {
     $lookup:
       {
         from: "collection",
         localField: "parent",
         foreignField: "_id",
         as: "myParent"
       }
  }
] )

Thanks
Pavel

Thanks Pavel, really helpful!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.