例子:
> 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
当前回答
假设你想在“表”中搜索“列”,并且你想进行不区分大小写的搜索。最有效的方法是:
//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”作为选项设置的不敏感标准进行搜索。
其他回答
db.company_profile.find({ "companyName" : { "$regex" : "Nilesh" , "$options" : "i"}});
聚合框架在mongodb 2.2中引入。您可以使用字符串操作符"$strcasecmp"在字符串之间进行不区分大小写的比较。它比使用regex更值得推荐,也更简单。
下面是关于聚合命令操作符的官方文档:https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp。
正如你在mongo docs中看到的那样——自3.2版以来$text索引默认情况下是不区分大小写的:https://docs.mongodb.com/manual/core/index-text/#text-index-case-insensitivity
创建一个文本索引并在查询中使用$text操作符。
记住前面的例子:
db.stuff.find( { foo: /bar/i } );
将导致每个包含bar的条目匹配查询(bar1, barxyz, openbar),这可能是非常危险的用户名搜索认证功能…
您可能需要使用适当的regexp语法使其仅匹配搜索项,如下:
db.stuff.find( { foo: /^bar$/i } );
有关正则表达式的语法帮助,请参阅http://www.regular-expressions.info/
假设你想在“表”中搜索“列”,并且你想进行不区分大小写的搜索。最有效的方法是:
//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”作为选项设置的不敏感标准进行搜索。