使用 mongodb $in 的不区分大小写的过滤器
Case insensitive filter using mongodb $in
我正在尝试使用 mongodb 查询制作不区分大小写的过滤器。我的代码-
var brand = req.query['Brand'].split(',');
query['genetal.brand'] = {$in:brand};
我无法在每个 $in 中添加 /^ / 正则表达式 item.Or 是否有任何其他方法可以找到 .
使用 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]}});
Returns:
/* 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] };
我正在尝试使用 mongodb 查询制作不区分大小写的过滤器。我的代码-
var brand = req.query['Brand'].split(',');
query['genetal.brand'] = {$in:brand};
我无法在每个 $in 中添加 /^ / 正则表达式 item.Or 是否有任何其他方法可以找到 .
使用 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]}});
Returns:
/* 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] };