Using variables in $in

Viewed 32

I have a request variable defined and for some reason I cannot use it in the $in block:

{
  $lookup: {
    from: 'users',
    as: 'user',
    let: {
      "blogIds": "$blog.id"
    },
    pipeline: [{
        $project: {
          id: 1,
          user_name: 1,
          picture: 1,
          blogs: 1
        },
      },
      {
        $match: {
          blogs: {
            $in: ["$$blogIds"]
          }
        }
      },
    ]
  }
}

What am I doing wrong?

if i try to send without $match, but with `$addFields:

{
  $lookup: {
    from: 'users',
    as: 'user',
    let: {
      "blogIds": "$blog.id"
    },
    pipeline: [{
        $project: {
          id: 1,
          user_name: 1,
          picture: 1,
          blogs: 1
        },
      },
      {
        $addFields: {
          field: "$$blogIds"
        }
      },
    ]
  }
}

enter image description here

Document example:

enter image description here

lorem ipsum dolor amen.

1 Answers

You can not use internal fields as input of another internal field,

There is a other way expression $expr operator to handle this situation, $expr can build query expressions that compare fields from the same document in a $match stage.

{ $match: { $expr: { $in: ["$$blogIds", "$blogs"] } } }
Related