how to make case insensitive query using variable?

Viewed 71

I already have a user with a username Kevin in my database. I want prevent new users to pick Kevin, kevin, KeViN, etc. as their username when creating an account. How do I modify my query to check if such user exists ignoring case-sensitivity?

def validate_username(self, username):
    if db.users.find_one({"username":username}):
        raise ValidationError("username is already taken")
3 Answers

Not sure if it’s available on mongo directly. as an alternative, add another field to your user document and while saving username convert it into lowercase and save the hash-code in hash-code field.

So username : Kevin , hashcode : (hashcode of “kevin”)

Next time when a user enters Username : KeViN , hashcode : (hashcode of kevin)

Not if you put a validation or unique key constraint on handcode.. it should solve it.

db.users.find({ "username" : { "$regex" : username , "$options" : "i"}});

or

db.users.find({'username':{'$regex' : '^username$', '$options' : 'i'}})

just put a "case-insensitive unique index" on the username field.

if someone enters an existing username, mongo will throw a duplicate key error which you can handle in your code and ask the user to enter another username.

you can create the index like this:

db.collection.createIndex(
    {
        username: "username_idx",
        unique: true,
        collation: {
            locale: "en",
            strength: 2
        }
    }
)
Related