[英]mongodb aggregate - match $nin array regex values
必须在 mongo 3.4 版中工作
嗨,作为聚合相关标签的一部分,我想返回具有未包含在script_url
数组中的whiteList
的标签。
问题是,我想将script_url
与数组值的正则表达式进行比较。
我有这个预测:
{
"script_url" : "www.analytics.com/path/file-7.js",
"whiteList" : [
null,
"www.analytics.com/path/*",
"www.analytics.com/path/.*",
"www.analytics.com/path/file-6.js",
"www.maps.com/*",
"www.maps.com/.*"
]
}
此$match
将script_url
与确切的whiteList
值进行比较。 因此,上面给出的文档在不应该通过的时候通过,因为它有www.analytics.com/path/。 * 在whiteList
中
{
"$match": {
"script_url": {"$nin": ["$whiteList"]}
}
}
如何将script_url
与whiteList
的正则表达式值匹配?
更新
我能够在我的聚合中达到这个阶段:
{
"script_url" : "www.asaf-test.com/path/file-1.js",
"whiteList" : [
"http://sd.bla.com/bla/878/676.js",
"www.asaf-test.com/path/*"
],
"whiteListRegex" : [
"/http:\/\/sd\.bla\.com\/bla\/878\/676\.js/",
"/www\.asaf-test\.com\/path\/.*/"
]
}
但是$match
并没有像它假设的那样过滤掉这个script_url
,因为它比较了文字字符串并且没有将数组值转换为正则表达式值。 有没有办法使用v3.4将数组值转换为$map
中的正则表达式值?
我知道您特别提到了 v3.4,但我找不到使用 v3.4 使其工作的解决方案。
因此,对于其他限制较少且能够使用 v4.2 的人来说,这是一种解决方案。
仅适用于 4.2 或更高版本
诀窍是使用$regexMatch
(可从 v4.2 获得)在whitelist
上使用 $ $filter
,如果过滤后的数组为空,则意味着script_url
与whitelist
中的任何内容都不匹配
db.collection.aggregate([
{
$match: {
$expr: {
$eq: [
{
$filter: {
input: "$whiteList",
cond: {
$regexMatch: { input: "$script_url", regex: "$$this" }
}
}
},
[]
]
}
}
}
])
也可以使用$reduce
代替$filter
db.collection.aggregate([
{
$match: {
$expr: {
$not: {
$reduce: {
input: "$whiteList",
initialValue: false,
in: {
$or: [
{
$regexMatch: { input: "$script_url", regex: "$$this" }
},
"$$value"
]
}
}
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.