例子:

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

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

当前回答

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

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

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

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

其他回答

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

记住前面的例子:

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

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

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

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

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

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


 

如果你正在使用MongoDB Compass:

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

对于使用Mongoose的Node.js:

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

假设你想在“表”中搜索“列”,并且你想进行不区分大小写的搜索。最有效的方法是:

//create empty JSON Object
mycolumn = {};

//check if column has valid value
if(column) {
    mycolumn.column = {$regex: new RegExp(column), $options: "i"};
}
Table.find(mycolumn);

它只是将您的搜索值添加为RegEx,并使用“i”作为选项设置的不敏感标准进行搜索。