2

I am trying to populate a deeply nested object in an array for quite some time but is of no luck. I tried unwinding the array but the resultant array is being converted into an object instead of an array.

let aggQuery: any = [
            { $match: {} }
    
            {
                $lookup: {
                    from: "tribe-answers", localField: "answers", foreignField: "_id", as: "answers"
                }
            },
             {
                "$unwind": {
                "path": "$answers.createdBy",
                "preserveNullAndEmptyArrays": true
                }
            },
            {
            $lookup: {
                from: "users", localField: "answers.createdBy", foreignField: "_id", as: "answers.createdBy"
            }
            },
            
        ];

Expected output

answers = [
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 },
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 }
]

Returned Output

answers = {
   _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 }

The above query does populate the createdBy field but turns the array into an object. What I need is to populate the createdBy field in every element of an array of answers. Thanks for the help.

Rajat
  • 45
  • 5

1 Answers1

2
db.getCollection('tribe-posts').aggregate([
    { 
        "$lookup": {
           "from": "tribe-answers",
            "let": {answerIds: "$answers"},
            "pipeline": [
                { "$match": { "$expr": { "$in": [ "$_id", "$$answerIds" ] } } },
                {$lookup: { from: "users", localField: "createdBy", foreignField: "_id", as: "createdBy" }},
                {"$unwind": {"path": "$createdBy","preserveNullAndEmptyArrays": true} }
                
            ],
            "as": "answers"
        }    
    },
])

This will produce the expected output

answers = [
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 },
 { _id,
  content
  createdBy{
     _id
     firstname
     lastname
  }
 }
]
Manoj Selvin
  • 2,247
  • 24
  • 20