我正在尝试使用mongodb查询进行不区分大小写的过滤器。我的代码 -
var brand = req.query['Brand'].split(',');
query['genetal.brand'] = {$in:brand};
我无法在每个$ in item中添加/ ^ / regex。或者还有其他任何方法可供查找。
答案 0 :(得分:1)
使用 RegExp object constructor 从字符串创建正则表达式。您需要先更新字符串以包含管道,即创建一个用管道替换逗号的正则表达式匹配,然后在查找查询中使用一个正则表达式,而不是它们的数组,如[/a|b|c/i]
。
用mongo shell来说明上述内容:
// insert test documents
db.product.insert({x: "A"});
db.product.insert({x: "b"});
db.product.insert({x: "c"});
db.product.insert({x: "d"});
db.product.insert({x: "e"});
var brands = "a,b,c";
var pipe = brands.replace(/[ ]*,[ ]*|[ ]+/g, "|") // same as var pipe = "a|b|c";
var re = new RegExp(pipe, "i"); // same as var re = /a|b|c/i;
db.product.find({"x": {"$in": [re]}});
<强>返回强>:
/* 0 */
{
"_id" : ObjectId("552b7c869c752469483ce9c2"),
"x" : "A"
}
/* 1 */
{
"_id" : ObjectId("552b7c869c752469483ce9c3"),
"x" : "b"
}
/* 2 */
{
"_id" : ObjectId("552b7c869c752469483ce9c4"),
"x" : "c"
}
所以你最终的代码应该是这样的:
var pipe = req.query['Brand'].replace(/[ ]*,[ ]*|[ ]+/g, "|");
var re = new RegExp(pipe, "i");
query['genetal.brand'] = {"$in": [re] };