Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo $in query with case-insensitivity

I'm using Mongoose.js to perform an $in query, like so:

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

friends is just an array of strings. However, I'm having some case issues, and wondering if I can use Mongo's $regex functionality to make this $in query case-insensitive?

like image 237
benhowdle89 Avatar asked Oct 31 '25 14:10

benhowdle89


2 Answers

From the docs:

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

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

One way is to create regular Expression for each Match and form the friends array.

 var friends = [/^name1$/i,/^name2$/i];
 or,
 var friends = [/^(name1|name2)$/i]
 userModel.find({"twitter_username":{$in:friends }})
like image 193
BatScream Avatar answered Nov 03 '25 12:11

BatScream


Its a little tricky to do something like that

at first you should convert friends to new regex array list 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 the sample documents in test collection

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

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

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

like image 29
2 revs, 2 users 67% Avatar answered Nov 03 '25 12:11

2 revs, 2 users 67%