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

后端 未结 24 1899
谎友^
谎友^ 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条回答
  •  -上瘾入骨i
    2020-11-22 05:18

    Keep in mind that the previous example:

    db.stuff.find( { foo: /bar/i } );
    

    will cause every entries containing bar to match the query ( bar1, barxyz, openbar ), it could be very dangerous for a username search on a auth function ...

    You may need to make it match only the search term by using the appropriate regexp syntax as:

    db.stuff.find( { foo: /^bar$/i } );
    

    See http://www.regular-expressions.info/ for syntax help on regular expressions

提交回复
热议问题