Kevin H.
Kevin H.

Reputation: 742

MongoDB $lookup to replace only the ID in an array of objects

I have the following example JSON-object saved in my mongodb-collection named "Profile"

{
   name: "Test",
   relations: [
      { 
          personid: <MongoDB-ID>, 
          type: "Friend", 
          duration: 5 
      },
      { 
          personid: <MongoDB-ID>, 
          type: "Family", 
          duration: 9 
      },
   ]
}

I've used the mongoose-Aggregate function because i need to add artificial fields based on caluclation in the documents saved. At the end of my aggregation i use the $lookup-function to replace the property "personID" in the objects inside of the "relations"-array.

{
   $lookup:
     {
       from: PersonModel.collection.name,
       localField: 'relations.personid',
       foreignField: '_id',
       as: "relations.personid"
     }
} 

Because i want each "person" in the array of objects to replaced within the populated from the specific person-document. This does not work as expected. I also tried to call ".populate()" on the result returned by the aggregate function which also not worked.

Upvotes: 1

Views: 1392

Answers (1)

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14412

Setting localField to relations.personid is not supported. localField either needs to point to an array where each member is used for the join or be a plain value. The usual way of getting around this is to $unwind first, perform the lookup, and then $group back if needed.

Upvotes: 1

Related Questions