How to use array of objects in let property in $lookup operator?

Collection: events

{
    "_id": ObjectId("613b8492bca3f52647f190e3"),
    "age": {
        "min": 16,
        "max": 18
    },
    "title": "First time in London!",
    "description": "Lorem ipsum dolor met",
    "address": {
        "location": {
            "type": "Point",
            "coordinates": [27, 72]
        },
        "name": "Surat, Gujarat"
    },
    "is_free": true,
    "starts_at": "2021-07-31T18:30:00.000Z",
    "type": "straight",
    "bookings": {
        "base_fee": 0,
        "users": [
            {
            "user": ObjectId("613b784abca3f52647f190df"),
            "liked_by_me": [
                {
                    ObjectId("613b7fa2bca3f52647f190e2")
                },
                {
                    ObjectId("613b7f71bca3f52647f190e0")
                }
            ],
            "liked_by_others": [
                {
                    ObjectId("613b784abca3f52647f190df")
                },
                {
                    ObjectId("613b7f89bca3f52647f190e1")
                }
            ]
        }]
    }
}

The below query works but I want to limit the projection

db.collection.events.aggregate(
[
  {
    '$lookup': {
      'from': 'users', 
      'localField': 'bookings.users.*.user',
      'foreignField': 'id',
      'as': 'participants'
    }
  }
])

So, I searched and it seems we can use $project if we use the new syntax with let & pipeline. But this is not working.

{
    $lookup: {
        'from': 'users',
        'let': { 'users': '$bookings.users.*.user' }, 
        'pipeline': [
            {
                '$match': {
                    '$expr': {
                        '$in': [ '$_id', '$$users' ]
                    }
                }
            }
        ],
        'as': 'participants'
    }
}

Make sure you are on version 5.0 and then you can add pipeline to regular $lookup you are already using.

Asya
P.S. I don’t really understand bookings.users.*.user' - it should just be bookings.users.user'

1 Like

Ah, right, bookings.users.user works. Actually, I thought that since it’s an array of objects it should be prefixed with an asterisk.