$lookup aggregation on nested array

Hey everyone,
I have this schema

  userId
  username
  displayName
  createdAt
  avatarUrl
  stats {
    followers [
      {
        followerId:
      }
    ]
  }

I’d like to make $lookup aggregation to get the entire user schema into follower object in “stats.followers”.
I tried something like this but it doesn’t work

    {$lookup: {
      from: "users",
      localField: "stats.followers.userId",
      foreignField: "userId",
      as: "stats.followers.userData"
    }}

I want to get follower data for every single follower object in “stats.followers”
Thank you for your help.

1 Like

Consider not storing followers as an array of objects, but as an array of references:

stats {
  followers [
    followerId
  ]
}

Then, you can just populate whole followers array with lookup. You can do it like this:

db.users.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "stats.followers",
      "foreignField": "userId",
      "as": "stats.followers.userData"
    }
  }
])

Working example

1 Like