MongoDB $regex使用问题:无法匹配名称含FOO的客户
问题出在正则表达式的写法上!
你现在的查询条件{'name': '/FOO/'}是把正则表达式当成了普通字符串来用,MongoDB会去精确匹配名称等于"/FOO/"的客户,而不是做模糊匹配——这就是为什么明明有包含FOO的客户却查不到啦!
要实现你想要的"名称包含FOO"或者"以FOO开头"的查询,得用MongoDB支持的正则表达式写法,有两种常用方式:
直接用正则字面量(适合固定关键词的场景):
匹配包含FOO的名称:Customer.find({'name': /FOO/}).exec(function (err, customer) { console.log(customer); })要是想忽略大小写,加个
i标志就行:/FOO/i
要是只想匹配以FOO开头的名称,就用/^FOO/(^表示字符串开头)用
RegExp构造函数(适合动态生成关键词的场景,比如从用户输入获取):const target = 'FOO'; // 匹配包含FOO的名称 Customer.find({'name': new RegExp(target)}).exec(function (err, customer) { console.log(customer); }) // 匹配以FOO开头的名称 Customer.find({'name': new RegExp(`^${target}`)}).exec(function (err, customer) { console.log(customer); })
你之前用{'name': 'FOO'}能查到,是因为这个是精确匹配——刚好有客户的名称就是FOO,但这不是你想要的模糊匹配效果哦。
内容的提问来源于stack exchange,提问作者Sithys
相关产品推荐
相关产品推荐

