'Mongodb elemMatch not reading variable from aggregate root

I'm trying to build an aggregate query from a users collection. Each user has an id property that is associated in a clients collection array:

// users...
[
  {
    id: '12345',
    name: 'John'
  }
  // ...
}
// clients...
[
  {
    name: 'Foo',
    members: [ { id: '1234', role: 'Admin' } ]
  },
  // ....
]

So what I'm trying to do is aggregate the users collection and do a $lookup to "join" the clients with which a user is a member (by the id)

db.users.aggregate([
  $lookup: {
      from: 'clients',
      as: 'clients',
      let: { user_id: '$id' },
      pipeline: [
        {
          $match: {
            members: {
              $elemMatch: { id: '$user_id' },
            },
          },
        },
      ],
    };
}])

If I hard-code any user's id into the $elemMatch (replacing $user_id) it works, but I can't seem to get it to work as a variable from the user records.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source