例子:

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

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

当前回答

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

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

其他回答

如果你正在使用MongoDB Compass:

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

对于使用Mongoose的Node.js:

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

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

  const flavorExists = await Flavors.findOne({
    'flavor.name': { $regex: flavorName, $options: 'i' },
  });

搜索变量并转义:

const escapeStringRegexp = require('escape-string-regexp')
const name = 'foo'
db.stuff.find({name: new RegExp('^' + escapeStringRegexp(name) + '$', 'i')})   

转义变量可以保护查询不受'攻击。*'或其他正则表达式。

escape-string-regexp

db.zipcodes.find({city : "NEW YORK"}); // Case-sensitive
db.zipcodes.find({city : /NEW york/i}); // Note the 'i' flag for case-insensitivity

我很惊讶没有人警告通过使用/^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()