soulzap
soulzap

Reputation: 69

Regex inside mongodb lookup pipeline stage

How can I perform a regex search inside the pipeline stage of a lookup?

{
    $lookup: {
        from: 'collection',
        let: {variable: '$localVariable', name: '$name'},
        pipeline:[{
            $match:{
                $expr:{
                    $and: [
                        {'$name': {$regex: '.*$$name.*', $options: 'i'}},
                        {$in: ['$_id', '$$variable']}
                    ]
                }
            }
        }],
        as: 'newDocument'
    }
},

I've tried a couple of things, and I'm pretty sure that the regex stage should be wrappen inside another operator, just not sure which one?

Upvotes: 1

Views: 1145

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

For Mongo version 4.2+ you can use $regexMatch

db.collection.aggregate([
  {
    $lookup: {
      from: "other",
      let: {
        name: "$name"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $regexMatch: {
                input: "$name",
                regex: "$$name",
                options: "i"
              }
            }
          }
        }
      ],
      as: "newDocument"
    }
  }
])

Mongo Playground

Upvotes: 3

Related Questions