Mongo $ in case insensitive request

I use Mongoose.js to execute the $ request in the following order:

userModel.find({ 'twitter_username': { $in: friends } }) 

friends is just an array of strings. However, I am having some problems and wondering if I can use the Mongo $ regex functionality to make this $ in a case insensitive question?

+3
source share
3 answers

From docs :

To include a regular expression in the $ expression in a query, you can only use JavaScript regular expression objects (i.e. / pattern /). For example:

{name: {$ in: [/ ^ acme / i, / ^ ack /]}}

One way is to create a regular expression for each match and form an array of friends.

  var friends = [/^name1$/i,/^name2$/i]; or, var friends = [/^(name1|name2)$/i] userModel.find({"twitter_username":{$in:friends }}) 
+3
source

It's a little hard to do something like that

you must first convert friends to a new array of regular expression arrays with:

 var insesitiveFriends = []; friends.forEach(function(item) { var re = new RegExp(item, "i"); insesitiveFriends.push(re); }) 

then run the query

 db.test.find( { 'twitter_username': { $in: insesitiveFriends } }) 

I have sample documents in a test collection

 /* 0 */ { "_id" : ObjectId("5485e2111bb8a63952bc933d"), "twitter_username" : "David" } /* 1 */ { "_id" : ObjectId("5485e2111bb8a63952bc933e"), "twitter_username" : "david" } 

and with var friends = ['DAvid','bob']; I received both documents

+4
source

Unfortunately, mongodb tends to be case sensitive in the kernel. You have several options:

1) Create a separate field that is a lowercase version of twitter_username and indexes it instead. Your object would have twitter_username and twitter_username_lc. Non-lowerecase, which you can use for display, etc., But lowercase, which you index and use in your where clause, etc.

This is the route that I have chosen for my application.

2) Create a really ugly regular expression from your username string in a loop before your search, and then pass it:

 db.users.find({handle:{$regex: /^benhowdle89|^will shaver|^superman/i } }) 

Note that using β€œstarts with” ^ carrots is best if the field is indexed.

0
source

Source: https://habr.com/ru/post/1012948/


All Articles