我需要使用 $cond 来组合不同的列,我需要写的一个 $cond 如下:
create_widget: {
$sum:{
$cond:[{$and: [ {$eq: ['$Method', 'POST']},
{Url:{$regex: /.*\/widgets$/}} ]}, 1, 0]
}
}
Run Code Online (Sandbox Code Playgroud)
而且这段代码不对,好像正则表达式不能放在这里。有没有其他方法可以做到这一点?我想匹配 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"}
Run Code Online (Sandbox Code Playgroud)
我写的整个代码如下:
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'}
}}
]);
Run Code Online (Sandbox Code Playgroud)
示例代码的预期结果是
{ "_id" : "a", "distinct_session" : 2, "create_widget" : 1 }
{ "_id" …Run Code Online (Sandbox Code Playgroud)