Querying MongoDB (via pymongo) in case insensitive efficiently

前端 未结 2 461
耶瑟儿~
耶瑟儿~ 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:53

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

提交回复
热议问题