例子:
> 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
当前回答
如果查询中有一些特殊字符,则regex simple将不起作用。您需要转义这些特殊字符。
以下helper函数可以在不安装任何第三方库的情况下提供帮助:
const escapeSpecialChars = (str) => {
return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
你的问题会是这样的:
db.collection.find({ field: { $regex: escapeSpecialChars(query), $options: "i" }})
希望对大家有所帮助!
其他回答
如果需要从变量中创建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 } );
这样做的好处是更加程序化,或者如果您经常重用它,则可以通过提前编译它来提高性能。
对于任何使用Golang并希望使用mongodb和mgo godoc globalsign库进行区分大小写的全文搜索的人。
collation := &mgo.Collation{
Locale: "en",
Strength: 2,
}
err := collection.Find(query).Collation(collation)
假设你想在“表”中搜索“列”,并且你想进行不区分大小写的搜索。最有效的方法是:
//create empty JSON Object
mycolumn = {};
//check if column has valid value
if(column) {
mycolumn.column = {$regex: new RegExp(column), $options: "i"};
}
Table.find(mycolumn);
它只是将您的搜索值添加为RegEx,并使用“i”作为选项设置的不敏感标准进行搜索。
从MongoDB 3.4开始,执行快速不区分大小写搜索的推荐方法是使用不区分大小写索引。
我亲自给其中一位创始人发了邮件,请他把这个工作做好,他做到了!自2009年以来,JIRA上就有这个问题,许多人都要求提供这个功能。下面是它的工作原理:
通过指定强度为1或2的排序规则,可以创建不区分大小写的索引。你可以像这样创建一个不区分大小写的索引:
db.cities.createIndex(
{ city: 1 },
{
collation: {
locale: 'en',
strength: 2
}
}
);
你也可以在创建集合时指定一个默认的排序规则:
db.createCollection('cities', { collation: { locale: 'en', strength: 2 } } );
在这两种情况下,为了使用不区分大小写的索引,你需要在find操作中指定与创建索引或集合时使用的相同的排序规则:
db.cities.find(
{ city: 'new york' }
).collation(
{ locale: 'en', strength: 2 }
);
这将返回"New York", "New York", "New York"等。
其他的笔记
The answers suggesting to use full-text search are wrong in this case (and potentially dangerous). The question was about making a case-insensitive query, e.g. username: 'bill' matching BILL or Bill, not a full-text search query, which would also match stemmed words of bill, such as Bills, billed etc. The answers suggesting to use regular expressions are slow, because even with indexes, the documentation states: "Case insensitive regular expression queries generally cannot use indexes effectively. The $regex implementation is not collation-aware and is unable to utilize case-insensitive indexes." $regex answers also run the risk of user input injection.
这些已经用于字符串搜索进行了测试
{'_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