Abdulaziz.Musaileekh
Abdulaziz.Musaileekh

Reputation: 325

$lookup for each element in array mongo aggregation

I have users schema with people field containing viewers property which contains an array of ObjectIds as a reference of users collection itself for example

{
    "username": "user1",
    "password": "password",
    "email": "[email protected]",
    "people": [{
            "id": 1,
            "viewers": ["ObjectId....", "ObjectId...."]
        },
        {
            "id": 2,
            "viewers": ["ObjectId....", "ObjectId...."]
        }
    ]
}

What I need to do is $lookup for each element inside viewers the problem is when I use below pipeline is pushing the same viewers for each document

{
  $unwind: {
    path: "$people.viewers",
    preserveNullAndEmptyArrays: true
  }
},
{
  $lookup: {
    from: "users",
    localField: "people.viewers",
    foreignField: "_id",
    as: "people"
  }
},
{
  $unwind: {
    path: "$viewers",
    preserveNullAndEmptyArrays: true
  }
},
{
  $project: {
    username: 1,        
    "viewers.username": 1    
  }
},
{
  $group: {
    _id: "$_id",
    username: { $first: "$username" },    
    people: { $first: "$people" },
    viewers: { $push: "$viewers" }
  }
},
{
  $project: {
    username: 1,    
    "people.id": 1,
    "people.viewers": "$viewers"
  }
}

What is the wrong in that aggregation

Upvotes: 5

Views: 6336

Answers (1)

Ashh
Ashh

Reputation: 46491

You can try below aggregation in mongodb 3.4 and above

User.aggregate([
  { "$unwind": { "path": "$people", "preserveNullAndEmptyArrays": true }},
  { "$lookup": {
    "from": "users",
    "localField": "people.viewers",
    "foreignField": "_id",
    "as": "people.viewers"
  }},
  { "$group": {
    "_id": "$_id",
    "username": { "$first": "$username" },    
    "email": { "$first": "$email" },
    "people": { "$push": "$people" }
  }}
])

Upvotes: 5

Related Questions