Python MongoDB正则表达式:忽略大小写

17

我该如何指定一个忽略大小写的正则表达式:

regex = ".*" + filter + ".*";
config.gThingCollection.find({"name":{"$regex":regex}})

我希望过滤器是不区分大小写的,如何实现?

4个回答

33

尝试使用Python的正则表达式对象。 Pymongo将正确地对它们进行序列化:

import re
config.gThingCollection.find({"name": re.compile(regex, re.IGNORECASE)})

26

您可以在查询中使用MongoDB的正则表达式选项,例如:

config.gThingCollection.find({"name":{"$regex":regex, "$options": "i"}})

4
res = posts.find({"geography": {"$regex": 'europe', "$options": 'i'}})

# if you need use $not
import re
res = posts.find(
    {"geography": {"$not": re.compile('europe'), "$options": 'i'}})

2
您的代码应该像这样:

您的代码应该像这样:

regex = ".*" + filter + ".*";
config.gThingCollection.find({"name":{"$regex":regex, "$options":"i"}})

参考资料:http://docs.mongodb.org/v2.2/reference/operator/regex/

该链接提供了MongoDB v2.2版本正则表达式的相关操作符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接