Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB follow an index from a collection via regex case insensitive

I use various indexed collections in MongoDB where I make queries from a simple search engine. The point of the matter is that I can't find a way to do these Regex queries in case insensitive, i.e. the queried collection doesn't follow the index.

this is the situation:(This way the index is followed by the collection without problems)

var query = req.query.name;

function(callback) {
  collection3.find({$or:[{ firstname: new RegExp('^'+query)},
  { email: new RegExp('^'+query)}]}).toArray(function(err, result3){ 
    if (err) return callback(err);
     locals.result3 = result3;
     callback();
  });
 },
 .........
 .........

I have tried in all possible ways but I cannot get the desired result, and I cannot find information specific to my problem, I have tried with:

collection3.find({$or:[{ firstname: new RegExp('^' +query+ '$', 'i')}, ......
collection3.find({$or:[{ firstname: new RegExp('^' +query,'i')}, ......
collection3.find({$or:[{ firstname: { $regex: query, $options: 'i' }},......
collection3.find({$or:[{ firstname: { $regex: new RegExp(`^${query}$`), $options: 'i'}},......

I also tried to bind it from the variable in various ways including:

var value = '^'+query;
var value = /^query/i;

` In short, since there does not seem to be one solution I would be grateful to anyone who helps me!

other ways of dealing with the problem would also be great Thanks!

like image 858
scofx Avatar asked Dec 22 '25 15:12

scofx


1 Answers

If you just need a case insensitive search, use a collation. Create the indexes with the collation specifying case-insensitive:

collection3.createIndex({name: 1},{collation: {locale: "en", strength: 1, caseLevel: false}} ) 
collection3.createIndex({name: 1},{collation: {locale: "en", strength: 1, caseLevel: false}} ) 

And use the same collation when querying:

collection3.find({$or:[{name:query},{email:query}]}).collation({locale:"en",strength:1,caseLevel:false})
like image 102
Joe Avatar answered Dec 24 '25 05:12

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!