例子:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
例子:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
当前回答
如果需要从变量中创建regexp,那么这是一种更好的方法:https://stackoverflow.com/a/10728069/309514
然后你可以这样做:
var string = "SomeStringToFind";
var regex = new RegExp(["^", string, "$"].join(""), "i");
// Creates a regex of: /^SomeStringToFind$/i
db.stuff.find( { foo: regex } );
这样做的好处是更加程序化,或者如果您经常重用它,则可以通过提前编译它来提高性能。
其他回答
如果需要从变量中创建regexp,那么这是一种更好的方法:https://stackoverflow.com/a/10728069/309514
然后你可以这样做:
var string = "SomeStringToFind";
var regex = new RegExp(["^", string, "$"].join(""), "i");
// Creates a regex of: /^SomeStringToFind$/i
db.stuff.find( { foo: regex } );
这样做的好处是更加程序化,或者如果您经常重用它,则可以通过提前编译它来提高性能。
这些已经用于字符串搜索进行了测试
{'_id': /.*CM.*/} ||find _id where _id contains ->CM
{'_id': /^CM/} ||find _id where _id starts ->CM
{'_id': /CM$/} ||find _id where _id ends ->CM
{'_id': /.*UcM075237.*/i} ||find _id where _id contains ->UcM075237, ignore upper/lower case
{'_id': /^UcM075237/i} ||find _id where _id starts ->UcM075237, ignore upper/lower case
{'_id': /UcM075237$/i} ||find _id where _id ends ->UcM075237, ignore upper/lower case
记住前面的例子:
db.stuff.find( { foo: /bar/i } );
将导致每个包含bar的条目匹配查询(bar1, barxyz, openbar),这可能是非常危险的用户名搜索认证功能…
您可能需要使用适当的regexp语法使其仅匹配搜索项,如下:
db.stuff.find( { foo: /^bar$/i } );
有关正则表达式的语法帮助,请参阅http://www.regular-expressions.info/
我很惊讶没有人警告通过使用/^bar$/ I正则表达式注入的风险,如果bar是密码或帐户id搜索。例如,bar => .*@myhackeddomain.com,所以我的打赌是:使用\Q \E正则表达式特殊字符!PERL提供
db.stuff.find( { foo: /^\Qbar\E$/i } );
当bar = '\E *@myhackeddomain.com\Q'时,您应该使用\\字符转义bar变量,以避免再次被\E利用
另一种选择是使用一个regex转义字符策略,就像这里描述的Javascript等价于Perl的\Q…\E或quotemeta()
在使用基于Regex的查询时要记住一件非常重要的事情——当您在登录系统中执行此操作时,转义正在搜索的每个字符,不要忘记^和$操作符。Lodash有一个很好的函数,如果你已经在使用它:
db.stuff.find({$regex: new RegExp(_.escapeRegExp(bar), $options: 'i'})
为什么?假设一个用户输入。*作为他的用户名。这将匹配所有用户名,只需猜测任何用户的密码就可以登录。