例子:
> 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
当前回答
搜索变量并转义:
const escapeStringRegexp = require('escape-string-regexp')
const name = 'foo'
db.stuff.find({name: new RegExp('^' + escapeStringRegexp(name) + '$', 'i')})
转义变量可以保护查询不受'攻击。*'或其他正则表达式。
escape-string-regexp
其他回答
记住前面的例子:
db.stuff.find( { foo: /bar/i } );
将导致每个包含bar的条目匹配查询(bar1, barxyz, openbar),这可能是非常危险的用户名搜索认证功能…
您可能需要使用适当的regexp语法使其仅匹配搜索项,如下:
db.stuff.find( { foo: /^bar$/i } );
有关正则表达式的语法帮助,请参阅http://www.regular-expressions.info/
这些已经用于字符串搜索进行了测试
{'_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
使用正则表达式, 如果任何其他选项都不适合您,RegExp是一个不错的选择。它使字符串不区分大小写。
var username = new RegExp("^" + "John" + "$", "i");;
使用用户名在查询,然后它完成。
我希望这对你也有用。愿一切都好!
在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()是一个属性,不会正确映射。
在使用基于Regex的查询时要记住一件非常重要的事情——当您在登录系统中执行此操作时,转义正在搜索的每个字符,不要忘记^和$操作符。Lodash有一个很好的函数,如果你已经在使用它:
db.stuff.find({$regex: new RegExp(_.escapeRegExp(bar), $options: 'i'})
为什么?假设一个用户输入。*作为他的用户名。这将匹配所有用户名,只需猜测任何用户的密码就可以登录。