vemund
vemund

Reputation: 1807

Aggregate and $lookup by $project field

I am trying to aggregate on my User collection and $project out the fields I need. Then I want to set let variables in $lookup to be able to use the variable to find matching documents.

I want to do it this way, because I will have many $lookups by the variables.

However I am not able to get this working correctly. What am I doing wrong with the variables?

$project: {
        _id: 1,
        name: 1,
        goal: 1
    }
},
{
    $lookup: {
        from: "goals",
        let: { user: "$_id" },
        pipeline: [
            {
                $match: {
                    "user": "$$user"
                }
            },
            { $project: { _id: 0, leads: 0 } },
        ],
        as: "goal"
    }
},
{
    $project: {
        _id: 1,
        name: 1,
        goal: 1
    }
},

Upvotes: 1

Views: 90

Answers (1)

Ashh
Ashh

Reputation: 46441

You need to use $expr to use variable name inside the $match stage.

{ $match: { $expr: { $eq: ['$user', '$$user'] }}}

Upvotes: 1

Related Questions