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

后端 未结 24 1891
谎友^
谎友^ 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:19

    I'm surprised nobody has warned about the risk of regex injection by using /^bar$/i if bar is a password or an account id search. (I.e. bar => .*@myhackeddomain.com e.g., so here comes my bet: use \Q \E regex special chars! provided in PERL

    db.stuff.find( { foo: /^\Qbar\E$/i } );
    

    You should escape bar variable \ chars with \\ to avoid \E exploit again when e.g. bar = '\E.*@myhackeddomain.com\Q'

    Another option is to use a regex escape char strategy like the one described here Javascript equivalent of Perl's \Q ... \E or quotemeta()

提交回复
热议问题