例子:

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

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

当前回答

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

其他回答

你可以使用正则表达式。

在你的例子中,这将是:

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

不过,我必须说,也许你可以降低(或提高)价值的过程中,而不是承担额外的成本,每次你找到它。显然,这对人名之类的东西不起作用,但可能用在像标签这样的用例上。

博士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


 

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

使用正则表达式, 如果任何其他选项都不适合您,RegExp是一个不错的选择。它使字符串不区分大小写。

var username = new RegExp("^" + "John" + "$", "i");;

使用用户名在查询,然后它完成。

我希望这对你也有用。愿一切都好!

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

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