erk*_*opi 7 regex mongodb conditional-statements
我需要使用 $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" : "b", "distinct_session" : 1, "create_widget" : 0 }
Run Code Online (Sandbox Code Playgroud)
对于MongoDB 4.2和更新的生产版本,以及 4.1.11 和更新的开发版本,使用$regexMatch
which 是一种语法糖$regexFind
,可用于正则表达式匹配和捕获。
db.tmpAll.aggregate([
{ "$group": {
"_id": {
"BrandId": "$BrandId",
"SessionId": "$SessionId"
},
"widget_count": {
"$sum": {
"$cond": [
{
"$and": [
{ "$eq": ["$Method", "POST"] },
{ "$regexMatch": {
"input": "$Url",
"regex": /widget/
} }
]
}, 1, 0
]
}
},
"session_count": { "$sum": 1 }
} },
{ "$group": {
"_id": "$_id.BrandId",
"create_widget": { "$sum": "$widget_count" },
"distinct_session": { "$sum": "$session_count" }
} }
]);
Run Code Online (Sandbox Code Playgroud)
此SERVER-8892对于不具有上述功能的较旧 MongoDB 版本,请在聚合管道中使用以下变通方法。$regex
$cond
存在一个未解决的 JIRA 问题-用作. 但是,作为一种变通方法,
它在$substr
操作$project
符阶段使用操作符来提取 URL 的一部分,并作为正则表达式的解决方法。:
db.tmpAll.aggregate([
{ "$group": {
"_id": {
"BrandId": "$BrandId",
"SessionId": "$SessionId"
},
"widget_count": {
"$sum": {
"$cond": [
{
"$and": [
{ "$eq": ["$Method", "POST"] },
{ "$eq": [ { "$substr": [ "$Url", 8, -1 ] }, "widget"] }
]
}, 1, 0
]
}
},
"session_count": { "$sum": 1 }
} },
{ "$group": {
"_id": "$_id.BrandId",
"create_widget": { "$sum": "$widget_count" },
"distinct_session": { "$sum": "$session_count" }
} }
]);
Run Code Online (Sandbox Code Playgroud)
输出
/* 1 */
{
"result" : [
{
"_id" : "a",
"create_widget" : 1,
"distinct_session" : 2
},
{
"_id" : "b",
"create_widget" : 0,
"distinct_session" : 1
}
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4800 次 |
最近记录: |