例子:
> 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);
});
}
其他回答
博士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
记住前面的例子:
db.stuff.find( { foo: /bar/i } );
将导致每个包含bar的条目匹配查询(bar1, barxyz, openbar),这可能是非常危险的用户名搜索认证功能…
您可能需要使用适当的regexp语法使其仅匹配搜索项,如下:
db.stuff.find( { foo: /^bar$/i } );
有关正则表达式的语法帮助,请参阅http://www.regular-expressions.info/
这些已经用于字符串搜索进行了测试
{'_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
我为不区分大小写的正则表达式创建了一个简单的Func,我在过滤器中使用它。
private Func<string, BsonRegularExpression> CaseInsensitiveCompare = (field) =>
BsonRegularExpression.Create(new Regex(field, RegexOptions.IgnoreCase));
然后,只需按如下方式筛选一个字段。
db.stuff.find({"foo": CaseInsensitiveCompare("bar")}).count();
最好的方法是在你选择的语言中,当为你的对象创建模型包装器时,让你的save()方法遍历一组你将搜索的字段,这些字段也被索引了;这组字段应该有对应的小写字母,然后用于搜索。
每次再次保存对象时,都会检查小写属性并更新主属性的任何更改。这将使您可以有效地搜索,但隐藏了每次更新lc字段所需的额外工作。
小写字段可以是一个键值对象存储,或者只是字段名加上前缀lc_。我使用第二种方法来简化查询(深度对象查询有时会令人困惑)。
注意:您希望索引lc_字段,而不是它们所基于的主字段。