例子:
> 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
当前回答
我很惊讶没有人警告通过使用/^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()
其他回答
对于任何使用Golang并希望使用mongodb和mgo godoc globalsign库进行区分大小写的全文搜索的人。
collation := &mgo.Collation{
Locale: "en",
Strength: 2,
}
err := collection.Find(query).Collation(collation)
如果查询中有一些特殊字符,则regex simple将不起作用。您需要转义这些特殊字符。
以下helper函数可以在不安装任何第三方库的情况下提供帮助:
const escapeSpecialChars = (str) => {
return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
你的问题会是这样的:
db.collection.find({ field: { $regex: escapeSpecialChars(query), $options: "i" }})
希望对大家有所帮助!
你可以使用正则表达式。
在你的例子中,这将是:
db.stuff.find( { foo: /^bar$/i } );
不过,我必须说,也许你可以降低(或提高)价值的过程中,而不是承担额外的成本,每次你找到它。显然,这对人名之类的东西不起作用,但可能用在像标签这样的用例上。
db.company_profile.find({ "companyName" : { "$regex" : "Nilesh" , "$options" : "i"}});
使用Mongoose对我来说很管用:
var find = function(username, next){
User.find({'username': {$regex: new RegExp('^' + username, 'i')}}, function(err, res){
if(err) throw err;
next(null, res);
});
}