Querying MongoDB (via pymongo) in case insensitive efficiently
Accepted answer is dangerous, it will match any string containing the username! Safe option is to match the exact string:
import re
db.stuff.find_one({'name': re.compile('^' + username + '$', re.IGNORECASE)})
Even safer, escape the variable of any special characters which might affect the regex match:
import re
db.stuff.find_one({'name': re.compile('^' + re.escape(username) + '$', re.IGNORECASE)})
PyMongo uses native python regular expressions, in the same way as the mongo shell uses native javascript regular expressions. To write the equivalent query of what you had written in the shell above, you would use:
db.stuff.find_one({'name': re.compile(username, re.IGNORECASE)})
Note that this will avoid using any index that may exist on the name
field, however. A common pattern for case-insensitive searching or sorting is to have a second field in your document, for instance name_lower
, which is always set whenever name
changes (to a lower-cased version of name
, in this case). You would then query for such a document like:
db.stuff.find_one({'name_lower': username.lower()})