Querying MongoDB (via pymongo) in case insensitive efficiently

前端 未结 2 463
耶瑟儿~
耶瑟儿~ 2021-02-04 00:19

I\'m currently creating a website in python (pyramid) which requires users to sign up and log in. The system allows for users to choose a username which can be a mixture of cap

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 00:35

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

提交回复
热议问题