例子:

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

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

当前回答

在使用基于Regex的查询时要记住一件非常重要的事情——当您在登录系统中执行此操作时,转义正在搜索的每个字符,不要忘记^和$操作符。Lodash有一个很好的函数,如果你已经在使用它:

db.stuff.find({$regex: new RegExp(_.escapeRegExp(bar), $options: 'i'})

为什么?假设一个用户输入。*作为他的用户名。这将匹配所有用户名,只需猜测任何用户的密码就可以登录。

其他回答

如果你正在使用MongoDB Compass:

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

对于使用Mongoose的Node.js:

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

如果查询中有一些特殊字符,则regex simple将不起作用。您需要转义这些特殊字符。

以下helper函数可以在不安装任何第三方库的情况下提供帮助:

const escapeSpecialChars = (str) => {
  return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

你的问题会是这样的:

db.collection.find({ field: { $regex: escapeSpecialChars(query), $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

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

//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”作为选项设置的不敏感标准进行搜索。

如果需要从变量中创建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 } );

这样做的好处是更加程序化,或者如果您经常重用它,则可以通过提前编译它来提高性能。