例子:
> 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
当前回答
使用Mongoose对我来说很管用:
var find = function(username, next){
User.find({'username': {$regex: new RegExp('^' + username, 'i')}}, function(err, res){
if(err) throw err;
next(null, res);
});
}
其他回答
如果你正在使用MongoDB Compass:
转到筛选器类型的集合-> {Fieldname: /string/i}
对于使用Mongoose的Node.js:
模型。find({FieldName: {$regex: "stringToSearch", $options: "i"}})
使用Mongoose对我来说很管用:
var find = function(username, next){
User.find({'username': {$regex: new RegExp('^' + username, 'i')}}, function(err, res){
if(err) throw err;
next(null, res);
});
}
你可以使用正则表达式。
在你的例子中,这将是:
db.stuff.find( { foo: /^bar$/i } );
不过,我必须说,也许你可以降低(或提高)价值的过程中,而不是承担额外的成本,每次你找到它。显然,这对人名之类的东西不起作用,但可能用在像标签这样的用例上。
你可以使用不区分大小写的索引:
下面的示例创建一个没有默认排序规则的集合,然后在名称字段上添加一个索引,排序规则不区分大小写。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
如果需要从变量中创建regexp,那么这是一种更好的方法:https://stackoverflow.com/a/10728069/309514
然后你可以这样做:
var string = "SomeStringToFind";
var regex = new RegExp(["^", string, "$"].join(""), "i");
// Creates a regex of: /^SomeStringToFind$/i
db.stuff.find( { foo: regex } );
这样做的好处是更加程序化,或者如果您经常重用它,则可以通过提前编译它来提高性能。