python mongodb regex: ignore case

Question:

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?

Asked By: Bin Chen

||

Answers:

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

import re
config.gThingCollection.find({"name": re.compile(regex, re.IGNORECASE)})
Answered By: Brendan W. McAdams

You can use MongoDB regex options in your query, something like this:

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

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/

Answered By: Mowd
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'}})
Answered By: Sérgio
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.