[英]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.