例子:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
例子:
> 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();
其他回答
搜索变量并转义:
const escapeStringRegexp = require('escape-string-regexp')
const name = 'foo'
db.stuff.find({name: new RegExp('^' + escapeStringRegexp(name) + '$', 'i')})
转义变量可以保护查询不受'攻击。*'或其他正则表达式。
escape-string-regexp
我也遇到过类似的问题,这对我很有帮助:
const flavorExists = await Flavors.findOne({
'flavor.name': { $regex: flavorName, $options: 'i' },
});
如果需要从变量中创建regexp,那么这是一种更好的方法:https://stackoverflow.com/a/10728069/309514
然后你可以这样做:
var string = "SomeStringToFind";
var regex = new RegExp(["^", string, "$"].join(""), "i");
// Creates a regex of: /^SomeStringToFind$/i
db.stuff.find( { foo: regex } );
这样做的好处是更加程序化,或者如果您经常重用它,则可以通过提前编译它来提高性能。
如果你正在使用MongoDB Compass:
转到筛选器类型的集合-> {Fieldname: /string/i}
对于使用Mongoose的Node.js:
模型。find({FieldName: {$regex: "stringToSearch", $options: "i"}})
对于任何使用Golang并希望使用mongodb和mgo godoc globalsign库进行区分大小写的全文搜索的人。
collation := &mgo.Collation{
Locale: "en",
Strength: 2,
}
err := collection.Find(query).Collation(collation)