例子:

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

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

当前回答

如果你正在使用MongoDB Compass:

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

对于使用Mongoose的Node.js:

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

其他回答

这些已经用于字符串搜索进行了测试

{'_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

Mongo(当前版本2.0.0)不允许对索引字段进行不区分大小写的搜索——请参阅它们的文档。对于非索引字段,其他答案中列出的正则表达式应该是可以的。

最好的方法是在你选择的语言中,当为你的对象创建模型包装器时,让你的save()方法遍历一组你将搜索的字段,这些字段也被索引了;这组字段应该有对应的小写字母,然后用于搜索。

每次再次保存对象时,都会检查小写属性并更新主属性的任何更改。这将使您可以有效地搜索,但隐藏了每次更新lc字段所需的额外工作。

小写字段可以是一个键值对象存储,或者只是字段名加上前缀lc_。我使用第二种方法来简化查询(深度对象查询有时会令人困惑)。

注意:您希望索引lc_字段,而不是它们所基于的主字段。

在c#中使用过滤器对我来说是有效的。

string s = "searchTerm";
    var filter = Builders<Model>.Filter.Where(p => p.Title.ToLower().Contains(s.ToLower()));
                var listSorted = collection.Find(filter).ToList();
                var list = collection.Find(filter).ToList();

它甚至可以使用索引,因为我相信方法是在返回发生后调用的,但我还没有测试出来。

这也避免了一个问题

var filter = Builders<Model>.Filter.Eq(p => p.Title.ToLower(), s.ToLower());

mongodb会认为p.t el . tolower()是一个属性,不会正确映射。

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

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