For MongoDB 4.2和更新的生产版本,以及在 4.1.11 和更新的开发版本中,使用$regexMatch https://docs.mongodb.com/manual/reference/operator/aggregation/regexMatch/这是一个语法糖$regexFind https://docs.mongodb.com/manual/reference/operator/aggregation/regexFind/#exp._S_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" }
} }
]);
There is an open JIRA issue for this SERVER-8892 - Use $regex as the expression in a $cond https://jira.mongodb.org/browse/SERVER-8892. However, as a workaround, For older MongoDB versions which do not have the above features, use the following workaround in your aggregation pipeline.
它使用$substr http://docs.mongodb.org/manual/reference/operator/aggregation/substr/运算符在$project http://docs.mongodb.org/manual/reference/operator/aggregation/project/#pipe._S_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" }
} }
]);
Output
/* 1 */
{
"result" : [
{
"_id" : "a",
"create_widget" : 1,
"distinct_session" : 2
},
{
"_id" : "b",
"create_widget" : 0,
"distinct_session" : 1
}
],
"ok" : 1
}