Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'like' or $regex query inside $cond in MongoDB

Please go through this question of mine:
MongoDB $group and explicit group formation with computed column

But this time, I need to compare strings, not numbers.The CASE query must have a LIKE:
CASE WHEN source LIKE '%Web%' THEN 'Web'

I then need to group by source. How to write this in Mongo? I am trying the following but not sure if $regex is supported inside $cond. By the way, is there a list of valid operators inside $cond somewhere? Looks like $cond isn't very fond of me :)

db.Twitter.aggregate(
    { $project: { 
        "_id":0,
        "Source": {
            $cond: [
                { $regex:['$source','/.* Android.*/'] },
                'Android', 
                { $cond: [
                    { $eq: ['$source', 'web'] }, 'Web', 'Others'
                ] } 
            ]
        }
    } }
);

There're many other values that I need to write in there, doing a deeper nesting. This is just an example with just 'Android' and 'Web' for the sake of brevity. I have tried both with $eq and $regex. Using $regex gives error of invalid operator whereas using $eq doesn't understand the regex expression and puts everything under 'Others'. If this is possible with regex, kindly let me know how to write it for case-insensitive match.

Thanks for any help :-)

like image 982
Aafreen Sheikh Avatar asked Jan 21 '13 15:01

Aafreen Sheikh


1 Answers

Well, it still seems to be not even scheduled to be implemented :( https://jira.mongodb.org/browse/SERVER-8892

I'm using 2.6 and took a peek on 3.0, but it's just not there.

There's one workaround though, if you can project your problem onto a stable substring. Then you can $substr the field and use multiple nested $cond. It's awkward, but it works.

like image 119
pkopac Avatar answered Oct 22 '22 02:10

pkopac