Use regex in $in operator using aggregation

Hi Team,

I faced issue while using regex pattern in $in Operator using aggregation.

{
  $match: { name: { $in: [ /tom/i, /harry/i ] }}
}

Above example works well with mongo compass but the same using in python wont work shows compile error near / .

I’ve tried using re package for this using pymongo in python base, but the aggregation query formed like below,

{
  $match: { name: { $in: [ re.compile('/tom/i'), re.compile('/harry/i') ] }}
}

Please suggest what is that issue or I’m missing something here.

Regards,
Jitendra.

You may always use Compass and export in the language of choice.

When I export

[
  {
    $match: { name: { $in: [ /tom/i, /harry/i ] }}
  }
]

to python3 it gives

[
    {
        '$match': {
            'name': {
                '$in': [
                    re.compile(r"tom(?i)"), re.compile(r"harry(?i)")
                ]
            }
        }
    }
]

I have not tested the above, so I hope it works.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.