MongoDB中$ cond内的'like'或$ regex查询 [英] 'like' or $regex query inside $cond in MongoDB

查看:716
本文介绍了MongoDB中$ cond内的'like'或$ regex查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请回答我的这个问题:
使用计算列的MongoDB $ group和显式组

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

但是这一次,我需要比较字符串,而不是数字.CASE查询必须具有LIKE:
CASE WHEN source LIKE '%Web%' THEN 'Web'

然后,我需要按来源分组.如何用Mongo编写?我正在尝试以下操作,但不确定$cond中是否支持$regex.顺便说一句,在$cond内某处是否有有效运算符的列表?看起来$cond不太喜欢我:)

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'
                ] } 
            ]
        }
    } }
);

我还需要在其中编写许多其他值,以进行更深入的嵌套.为了简洁起见,这只是"Android"和"Web"的示例.我已经尝试过同时使用$eq$regex.使用$regex会给出无效运算符的错误,而使用$eq则无法理解正则表达式,因此会将所有内容置于其他"下.如果使用正则表达式可以实现,请让我知道如何为不区分大小写的匹配编写它.

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.

感谢您的帮助:-)

推荐答案

好吧,它似乎仍未计划实施:( https://jira.mongodb.org/browse/SERVER-8892

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

我正在使用2.6,并在3.0上进行了窥视,但它还不存在.

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

但是,如果可以将问题投影到稳定的子字符串上,则有一种解决方法.然后,您可以$ substr字段并使用多个嵌套的$ cond.这很尴尬,但是有效.

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.

这篇关于MongoDB中$ cond内的'like'或$ regex查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆