Blabber
Blabber

Reputation: 349

Pymongo Regex match with list

I have a list of distinct strings.

lst = ['.\*123.\*','.\*252.\*','.\*812.\*','.\*135.\*']

I want to perform an aggregation operation such that my $match looks like the following:

 {"$match":{"Var":{"$in":lst}}}  

The var field in MongoDb records is a string containing numbers:
e.g. "abc123", "haaofalfa812", etc. I want to match this Var to a regular expression. If the variables in the lst were less, i could've done this...

{"$match":{"Var":{"$in":[re.compile('.*123.*'),re.compile('.*252.*'),re.compile('.*812.*')]}}}

But since it is a lst already initialized and contains a lot of elements, what should I do?

I tried the following but this doesn't work too...

{"$match":{"Var":{"$in":[re.compile(x for x in lst)]}}}  

I get the following error for obvious reasons.

TypeError: first argument must be string or compiled pattern

Upvotes: 0

Views: 808

Answers (1)

Maciej M
Maciej M

Reputation: 81

Your list comprehension is wrong. I reckon what you wanted to do is this:

[re.compile(x) for x in lst]

That TypeError comes from trying to pass generator(x for x in lst statement) to re.compile()

Upvotes: 3

Related Questions