Reputation: 85
i am trying to make case insensitive filter using mongodb query . my code -
var brand = req.query['Brand'].split(',');
query['genetal.brand'] = {$in:brand};
i am not able to add /^ / regex in every $in item.Or is there any other method to find .
Upvotes: 0
Views: 592
Reputation: 103305
Use the RegExp object constructor to create a regular expression from a string. You need to first update the string to include pipes, i.e. create a regex match that replaces comma with a pipe and then in your find query use one regex, not an array of them, like [/a|b|c/i]
.
To illustrate the above with 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"
}
So you final code should look like:
var pipe = req.query['Brand'].replace(/[ ]*,[ ]*|[ ]+/g, "|");
var re = new RegExp(pipe, "i");
query['genetal.brand'] = {"$in": [re] };
Upvotes: 1