例子:
> 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
当前回答
你可以使用不区分大小写的索引:
下面的示例创建一个没有默认排序规则的集合,然后在名称字段上添加一个索引,排序规则不区分大小写。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
其他回答
正如你在mongo docs中看到的那样——自3.2版以来$text索引默认情况下是不区分大小写的:https://docs.mongodb.com/manual/core/index-text/#text-index-case-insensitivity
创建一个文本索引并在查询中使用$text操作符。
使用Mongoose对我来说很管用:
var find = function(username, next){
User.find({'username': {$regex: new RegExp('^' + username, 'i')}}, function(err, res){
if(err) throw err;
next(null, res);
});
}
对于任何使用Golang并希望使用mongodb和mgo godoc globalsign库进行区分大小写的全文搜索的人。
collation := &mgo.Collation{
Locale: "en",
Strength: 2,
}
err := collection.Find(query).Collation(collation)
你可以使用正则表达式。
在你的例子中,这将是:
db.stuff.find( { foo: /^bar$/i } );
不过,我必须说,也许你可以降低(或提高)价值的过程中,而不是承担额外的成本,每次你找到它。显然,这对人名之类的东西不起作用,但可能用在像标签这样的用例上。
如果你正在使用MongoDB Compass:
转到筛选器类型的集合-> {Fieldname: /string/i}
对于使用Mongoose的Node.js:
模型。find({FieldName: {$regex: "stringToSearch", $options: "i"}})