例子:

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

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

当前回答

你可以使用不区分大小写的索引:

下面的示例创建一个没有默认排序规则的集合,然后在名称字段上添加一个索引,排序规则不区分大小写。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

其他回答

博士TL;

正确的方法做到这一点在mongo

不使用RegExp

使用mongodb的内置索引,搜索

第一步:

db.articles.insert(
   [
     { _id: 1, subject: "coffee", author: "xyz", views: 50 },
     { _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
     { _id: 3, subject: "Baking a cake", author: "abc", views: 90  },
     { _id: 4, subject: "baking", author: "xyz", views: 100 },
     { _id: 5, subject: "Café Con Leche", author: "abc", views: 200 },
     { _id: 6, subject: "Сырники", author: "jkl", views: 80 },
     { _id: 7, subject: "coffee and cream", author: "efg", views: 10 },
     { _id: 8, subject: "Cafe con Leche", author: "xyz", views: 10 }
   ]
)
 

第二步:

需要在你想要搜索的任何TEXT字段上创建索引,没有索引查询将会非常慢

db.articles.createIndex( { subject: "text" } )

第三步:

db.articles.find( { $text: { $search: "coffee",$caseSensitive :true } } )  //FOR SENSITIVITY
db.articles.find( { $text: { $search: "coffee",$caseSensitive :false } } ) //FOR INSENSITIVITY


 

如果你正在使用MongoDB Compass:

转到筛选器类型的集合-> {Fieldname: /string/i}

对于使用Mongoose的Node.js:

模型。find({FieldName: {$regex: "stringToSearch", $options: "i"}})

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

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

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

对于任何使用Golang并希望使用mongodb和mgo godoc globalsign库进行区分大小写的全文搜索的人。

collation := &mgo.Collation{
    Locale:   "en",
    Strength: 2, 
}


err := collection.Find(query).Collation(collation)