MongoDB: Is it possible to make a case-insensitive query?

后端 未结 24 1796
谎友^
谎友^ 2020-11-22 04:44

Example:

> db.stuff.save({\"foo\":\"bar\"});

> db.stuff.find({\"foo\":\"bar\"}).count();
1
> db.stuff.find({\"foo\":\"BAR\"}).count();
0

24条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 05:25

    One very important thing to keep in mind when using a Regex based query - When you are doing this for a login system, escape every single character you are searching for, and don't forget the ^ and $ operators. Lodash has a nice function for this, should you be using it already:

    db.stuff.find({$regex: new RegExp(_.escapeRegExp(bar), $options: 'i'})
    

    Why? Imagine a user entering .* as his username. That would match all usernames, enabling a login by just guessing any user's password.

提交回复
热议问题