简体   繁体   English

Pymongo正则表达式与列表匹配

[英]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看起来像下面这样:

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

The var field in MongoDb records is a string containing numbers: MongoDb记录中的var字段是一个包含数字的字符串:
eg "abc123", "haaofalfa812", etc. I want to match this Var to a regular expression. 例如“ abc123”,“ haaofalfa812”等。我想将此Var与正则表达式匹配。 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 TypeError:第一个参数必须是字符串或已编译的模式

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() TypeError来自尝试将生成器( x for x in lst语句中的x for x in lst )传递给re.compile()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM