失敗是因爲"$nick"
意在另一字段的值,但$match
這基本上是一個「普通的MongoDB查詢」之所以不具有的概念「從現有字段值使用變量」以便在條件上「匹配」。
因此,您應該使用"aggregation logical operators",它們使用$redact
流水線階段,或者直接使用$filter
「過濾」數組內容。
db.getCollection('summoners').aggregate([
{"$skip": 0},
{"$limit": 2},
{'$unwind': '$leagues'},
{'$unwind': '$leagues.entries'},
{'$redact': {
'$cond': {
'if': { '$eq': [ '$leagues.entries.playerOrTeamName', '$nick' ] }
'then': '$$KEEP',
'else': '$$PRUNE'
}
}
])
,其對所述的域值的「邏輯」的比較和決定"$$KEEP"
其中所述病症是從結果,其中它是false
true
或"$$PRUNE"
。
或者直接在陣列上,完整地保留:
db.getCollection('summoners').aggregate([
{ "$skip": 0 },
{ "$limit": 2 },
{ "$addFields": {
"leagues": {
"$filter": {
"input": {
"$map": {
"input": "$leagues",
"as": "l",
"in": {
"entries": {
"$filter": {
"input": "$$l.entries",
"as": "e",
"cond": { "$eq": [ "$$e.playerOrTeamName", "$nick" ] }
}
},
"name": "$$l.name",
"queque": "$$l.queque",
"tier": "$$l.tier"
}
}
},
"as": "l",
"cond": {
"$gt": [ { "$size": "$$l.entries" }, 0 ]
}
}
}
}}
])
其基本上通過施加$filter
到內"entries"
爲字段的比較陣列重新映射,並且其中所述「外」陣列不再有"entries"
中的任何結果都將被刪除。
提供的答案中是否有某些東西可以解決您的問題?如果是這樣,請**評論答案**以澄清究竟需要解決的問題。如果它確實回答了你問的問題,那麼請注意[**接受你的答案**](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)到你問的問題 –