是否可以在MongoDB的$ cond中编写正则表达式

时间:2015-05-13 16:58:33

标签: regex mongodb conditional-statements

我需要使用$ cond来组合differenet列,我需要写的一个$ cond如下:

create_widget: {
        $sum:{
          $cond:[{$and: [ {$eq: ['$Method', 'POST']},
                {Url:{$regex: /.*\/widgets$/}} ]}, 1, 0]
        }
    }

并且这段代码不对,看来,正则表达式不能放在这里。有没有其他方法可以做到这一点?我想匹配Url和正则表达式,并将代码放在$ cond。

示例数据显示为

{"BrandId":"a","SessionId":"a1","Method":"POST","Url":"/sample/widgets"}
{"BrandId":"a","SessionId":"a2","Method":"POST","Url":"/sample/blog"}
{"BrandId":"b","SessionId":"b1","Method":"PUT","Url":"/sample/widgets"}

我写的整个代码如下:

db.tmpAll.aggregate([
    {$group: {
        _id: {BrandId:'$BrandId'},
        SessionId: {$addToSet: '$SessionId'},
        create_widget: {
            $sum:{
              $cond:[{$and: [ {$eq: ['$Method', 'POST']},
                    {} ]}, 1, 0]
            }
        }
    }},
    {$group: {
        _id: '$_id.BrandId',
        distinct_session: {$sum: {$size: '$SessionId'}},
        create_widget: {$sum: '$create_widget'}
    }}
]);

示例代码的预期结果是

{ "_id" : "a", "distinct_session" : 2, "create_widget" : 1 }
{ "_id" : "b", "distinct_session" : 1, "create_widget" : 0 }

1 个答案:

答案 0 :(得分:2)

SERVER-8892 - Use $regex as the expression in a $cond 存在一个公开的JIRA问题。但是,作为解决方法,请使用以下聚合管道。它使用$substr运算符阶段中的$project运算符来提取URL的一部分,并充当正则表达式的变通方法。 :

db.tmpAll.aggregate([
    {
        "$project": {
            "BrandId": 1,
            "SessionId": 1,
            "IsWidget": { 
                 "$cond": [
                    {
                        "$and": [ 
                            { "$eq": ["$Method", "POST"] },
                            { "$eq": [ { "$substr": [ "$Url", 8, -1 ] }, "widget"] } 
                        ]
                    }, 1, 0
                 ]                     
            }
        }
    },
    {
        "$group": {
            "_id": {
                "BrandId": "$BrandId",
                "SessionId": "$SessionId"
            },
            "widget_count": {
                "$sum": "$IsWidget"
            },
            "session_count": {
                "$sum": 1
            }
        }
    },
    {
        "$group": {
            "_id": "$_id.BrandId",
            "create_widget": {
                "$sum": "$widget_count"
            },
            "distinct_session": {
                "$sum": "$session_count"
            }
        }
    }
]);

<强>输出

/* 1 */
{
    "result" : [ 
        {
            "_id" : "a",
            "create_widget" : 1,
            "distinct_session" : 2
        }, 
        {
            "_id" : "b",
            "create_widget" : 0,
            "distinct_session" : 1
        }
    ],
    "ok" : 1
}