[英]$match by aggregated hierarchy in MongoDB using Mongoose
我嘗試使用and-regex $match
以前由$graphLookup
記錄聚合的$graphLookup
。
我已經在mongoldb外殼中對其進行了測試,並且可以正常工作! 但是通過mongoose
破壞了相同的查詢返回空集。
(免責聲明:它與我之前的問題重疊了, 如何在MongoDB中匹配聚合的($ graphLookup)元素?但是偶爾我需要比match更靈活的方法,所以我決定再次詢問)
假設我有:
{ "_id": 1, "name": "Dev", final: false }
{ "_id": 2, "name": "Eliot", "reportsTo": "Dev", final: false }
{ "_id": 3, "name": "Ron", "reportsTo": "Eliot", final: false }
{ "_id": 4, "name": "Andrew", "reportsTo": "Eliot", final: false }
{ "_id": 5, "name": "Andron", "reportsTo": "Eliot", final: false }
{ "_id": 6, "name": "Asya", "reportsTo": "Ron", final: true }
{ "_id": 7, "name": "Dan", "reportsTo": "Andrew", final: true }
{ "_id": 8, "name": "Don", "reportsTo": "Andron", final: true }
按通話匯總
db.employees.aggregate([
{$match: { final: true }},
{$graphLookup: {
from: "employees",
startWith: "$reportsTo",
connectFromField: "reportsTo",
connectToField: "name",
as: "reporters"
}},
{$match: ???}
])
我需要添加什么正則表達式匹配來實現此目的:
{"_id": 7, "name": "Dan", "reportsTo": "Andrew", final: true,
"reporters": [
{ "_id": 1, "name": "Dev", final: false },
{ "_id": 2, "name": "Eliot", "reportsTo": "Dev", final: false },
{ "_id": 4, "name": "Andrew", "reportsTo": "Eliot", final: false }
]
},
{"_id": 8, "name": "Don", "reportsTo": "Andron", final: true,
"reporters": [
{ "_id": 1, "name": "Dev", final: false },
{ "_id": 2, "name": "Eliot", "reportsTo": "Dev", final: false },
{ "_id": 5, "name": "Andron", "reportsTo": "Eliot", final: false }
]
}
正如我建議的那樣,由於我的情況限制(必須動態生成regex規則),因此必須通過應用$match-$and-$regex
來正確解決,我無法准備斜線regex模式。
{$match:
{$and: [
{"reporters.name": {$regex: 'Andr(?:ew|on)'}},
{"reporters.name": {$regex: 'Eliot'}}
]}
}
它按預期工作。
db.employees.aggregate([
{$match: { final: true }},
{$graphLookup: {
from: "employees",
startWith: "$reportsTo",
connectFromField: "reportsTo",
connectToField: "name",
as: "reporters"
}},
{$match:
{$and: [
{"reporters.name": {$regex: 'Andr(?:ew|on)'}},
{"reporters.name": {$regex: 'Eliot'}}
]}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.