例子:

> db.stuff.save({"foo":"bar"});

> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0

当前回答

在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()是一个属性,不会正确映射。

其他回答

Mongo(当前版本2.0.0)不允许对索引字段进行不区分大小写的搜索——请参阅它们的文档。对于非索引字段,其他答案中列出的正则表达式应该是可以的。

正如你在mongo docs中看到的那样——自3.2版以来$text索引默认情况下是不区分大小写的:https://docs.mongodb.com/manual/core/index-text/#text-index-case-insensitivity

创建一个文本索引并在查询中使用$text操作符。

我为不区分大小写的正则表达式创建了一个简单的Func,我在过滤器中使用它。

private Func<string, BsonRegularExpression> CaseInsensitiveCompare = (field) => 
            BsonRegularExpression.Create(new Regex(field, RegexOptions.IgnoreCase));

然后,只需按如下方式筛选一个字段。

db.stuff.find({"foo": CaseInsensitiveCompare("bar")}).count();

聚合框架在mongodb 2.2中引入。您可以使用字符串操作符"$strcasecmp"在字符串之间进行不区分大小写的比较。它比使用regex更值得推荐,也更简单。

下面是关于聚合命令操作符的官方文档:https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp。

这些已经用于字符串搜索进行了测试

{'_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