例子:

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

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

当前回答

我也遇到过类似的问题,这对我很有帮助:

  const flavorExists = await Flavors.findOne({
    'flavor.name': { $regex: flavorName, $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);
    });
}

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

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

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

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

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

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

记住前面的例子:

db.stuff.find( { foo: /bar/i } );

将导致每个包含bar的条目匹配查询(bar1, barxyz, openbar),这可能是非常危险的用户名搜索认证功能…

您可能需要使用适当的regexp语法使其仅匹配搜索项,如下:

db.stuff.find( { foo: /^bar$/i } );

有关正则表达式的语法帮助,请参阅http://www.regular-expressions.info/

我很惊讶没有人警告通过使用/^bar$/ I正则表达式注入的风险,如果bar是密码或帐户id搜索。例如,bar => .*@myhackeddomain.com,所以我的打赌是:使用\Q \E正则表达式特殊字符!PERL提供

db.stuff.find( { foo: /^\Qbar\E$/i } );

当bar = '\E *@myhackeddomain.com\Q'时,您应该使用\\字符转义bar变量,以避免再次被\E利用

另一种选择是使用一个regex转义字符策略,就像这里描述的Javascript等价于Perl的\Q…\E或quotemeta()