例子:
> 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
当前回答
聚合框架在mongodb 2.2中引入。您可以使用字符串操作符"$strcasecmp"在字符串之间进行不区分大小写的比较。它比使用regex更值得推荐,也更简单。
下面是关于聚合命令操作符的官方文档:https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp。
其他回答
更新:
原来的答案现在已经过时了。Mongodb现在支持高级全文搜索,有很多特性。
最初的回答:
需要注意的是,使用regex的大小写不敏感/i进行搜索意味着mongodb不能通过索引进行搜索,因此针对大型数据集的查询可能需要很长时间。
即使数据集很小,效率也不是很高。cpu消耗比查询所保证的要大得多,如果您试图实现规模化,这可能会成为一个问题。
作为一种替代方法,您可以存储一个大写的副本并根据它进行搜索。例如,我有一个用户表,其中有一个混合大小写的用户名,但id是用户名的大写副本。这确保了区分大小写的复制是不可能的(同时拥有“Foo”和“Foo”是不允许的),并且我可以通过id = username. touppercase()进行搜索,以获得对用户名不区分大小写的搜索。
如果字段很大,比如消息体,复制数据可能不是一个好选择。我相信在这种情况下,使用像Apache Lucene这样的无关索引器是最好的选择。
假设你想在“表”中搜索“列”,并且你想进行不区分大小写的搜索。最有效的方法是:
//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 2.2中引入。您可以使用字符串操作符"$strcasecmp"在字符串之间进行不区分大小写的比较。它比使用regex更值得推荐,也更简单。
下面是关于聚合命令操作符的官方文档:https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp。
在c#中使用过滤器对我来说是有效的。
string s = "searchTerm";
var filter = Builders<Model>.Filter.Where(p => p.Title.ToLower().Contains(s.ToLower()));
var listSorted = collection.Find(filter).ToList();
var list = collection.Find(filter).ToList();
它甚至可以使用索引,因为我相信方法是在返回发生后调用的,但我还没有测试出来。
这也避免了一个问题
var filter = Builders<Model>.Filter.Eq(p => p.Title.ToLower(), s.ToLower());
mongodb会认为p.t el . tolower()是一个属性,不会正确映射。
你可以使用不区分大小写的索引:
下面的示例创建一个没有默认排序规则的集合,然后在名称字段上添加一个索引,排序规则不区分大小写。Unicode国际组件
/* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )
要使用索引,查询必须指定相同的排序规则。
db.users.insert( [ { name: "Oğuz" },
{ name: "oğuz" },
{ name: "OĞUZ" } ] )
// does not use index, finds one result
db.users.find( { name: "oğuz" } )
// uses the index, finds three results
db.users.find( { name: "oğuz" } ).collation( { locale: 'tr', strength: 2 } )
// does not use the index, finds three results (different strength)
db.users.find( { name: "oğuz" } ).collation( { locale: 'tr', strength: 1 } )
或者你可以创建一个默认排序规则的集合:
db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation