简体   繁体   中英

python mongodb regex: ignore case

How can I specify a REGEX and ignore the case:

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

I want the filter to be case-insensitive, how to achieve that?

Try using the python regex objects instead. Pymongo will serialize them properly:

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

您可以在查询中使用MongoDB正则表达式选项。

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

Your code should look like this:

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

Reference: http://docs.mongodb.org/v2.2/reference/operator/regex/

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'}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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