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

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

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

Then I need to group by source. How to write this in Mongo? I am trying to do the following, but not sure if $regex supported inside $cond . By the way, is there a list of valid operators inside $cond somewhere? It looks like $cond doesn't really like me :)

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

There are many other meanings that I need to write there, making a deeper nesting. This is just an example with the simplicity of “Android” and “Web” for short. I tried both with $eq and $regex . Using $regex gives an invalid operator error, while using $eq does not understand the regex expression and puts everything under "Other". If possible with a regex, kindly tell me how to write it for case insensitivity.

Thanks for any help :-)

+8
regex mongodb mongodb-query
source share
2 answers

Well, it looks like it’s not even planned to be implemented :( https://jira.mongodb.org/browse/SERVER-8892

I use 2.6 and looked in 3.0, but it just isn't there.

There is one workaround if you can project your problem onto a stable substring. Then you can $ substr field and use a few nested $ cond. This is inconvenient, but it works.

+1
source share

Perhaps you can try it with MapReduce.

 var map = function() { var reg1=new RegExp("(Android)+"); var reg2=new RegExp("(web)+"); if (reg1.test(this.source)){ emit(this._id,'Android'); } else if (reg2.test(this.source)) { emit(this._id,'web'); } } var reduce = function (key,value){ var reduced = { id:key, source:value } return reduced; } db.Twitter.mapReduce(map,reduce,{out:'map_reduce_result'}); db.map_reduce_result.find(); 

Instead of the MongoDB $ regular expression, you can use JavaScript regular expressions.

0
source share

All Articles