2017-07-19 77 views
1

我有具有以下結構的文檔的集合: enter image description here針對一個文件的值匹配的數組元素和過濾

兩個同盟和條目是我放鬆(陣列),但是然後我需要找到發生「文字的屬性」nick「顯示在」playerOrTeamName「上。

db.getCollection('summoners').aggregate([ 
    {"$skip": 0}, 
    {"$limit": 2}, 
    {'$unwind': '$leagues'}, 
    {'$unwind': '$leagues.entries'}, 
    {'$match': {'leagues.entries.playerOrTeamName': '$nick'}}, 
],{ 

allowDiskUse:真 })

爲什麼會在0的結果 「匹配」 部分結果呢?我可以保證玩家的暱稱將始終出現在條目數組中。

PS:用於簡單的緣故極限= 2

+0

提供的答案中是否有某些東西可以解決您的問題?如果是這樣,請**評論答案**以澄清究竟需要解決的問題。如果它確實回答了你問的問題,那麼請注意[**接受你的答案**](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)到你問的問題 –

回答

1

失敗是因爲"$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"其中所述病症是從結果,其中它是falsetrue"$$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"中的任何結果都將被刪除。

相關問題