How to use regex in the lookup pipeline?

If you are on 4.2 or later, you can adjust the suggestion from @Pavel_Duchovny and use this aggregation regex expression.

So if you have a previous stage which figures out the “starts with” substring, you can use that inside $expr after assigning it to a variable like you are doing.

The stage would be:

{$lookup: {
    from: 'ForeignCollection',
    let: { regex: {$concat:["^", '$ProductCode']}},
    pipeline: [
         { $match: {$expr: {
               $regexMatch:{
                   input: "$ProductSerial",
                   regex: "$$regex",
                   options: "i"
               }
        }}}
    ],
    as: "Product"
}}
4 Likes