2016-08-16 63 views
1

我有兩個集合users和`groups。讓我們假裝當前收藏中有以下數據。

users收集具有以下文件

{ 
    "_id":"57a944390b1acf0d069388c1", 
    "first":"John", 
    "last":"Smith", 
    "email":"[email protected]", 
    "groups":[ 
     { 
     "id":"57aab09c0b1acf135a6b6856", 
     "name":"Group A" 
     }, 
     { 
     "id":"57aab0ed0b1acf135a6b6857", 
     "name":"Group B" 
     }, 
     { 
     "id":"57b008be31a5a202ee4ff47b", 
     "name":"Group C" 
     } 
    ] 
} 

groups收集有以下兩個文件

[ 
    { 
     "_id":"57aab0ed0b1acf135a6b6857", 
     "name":"Group B", 
     "requests":[ 
     { 
      "_id":"57b14b1831a5a2756fbc9873", 
      "description":"Request A", 
      "denied_requests":[ ] 
     } 
     ] 
    } { 
     "_id":"57b008be31a5a202ee4ff47b", 
     "name":"Group C", 
     "requests":[ 
     { 
      "_id":"57b14c2131a5a2756fbc9874", 
      "description":"Request B", 
      "denied_requests":[ ] 
     }, 
     { 
      "_id":"57b14e3131a5a2756fbc9875", 
      "description":"Request C", 
      "denied_requests":[ 
       "57a944390b1acf0d069388c1" 
      ] 
     } 
     ] 
    } 
] 

我需要做的是使用聚合管道來查詢用戶的所有請求排除用戶拒絕的請求。

我想這將包括以下psudo步驟user_id作爲問題的輸入。

  • $match用戶_id字段
  • $project的組使用先前步驟
  • $lookup的結果id S上的id$projectusers.groupsgroups集合的_id
  • $matchrequests上,根據請求,沒有當前用戶標識denied_requests數組。

表示用戶_id採樣輸入

樣例輸入到這將是57a944390b1acf0d069388c1

樣本輸出

樣本輸出到這將是要求將下列表用戶沒有拒絕。

[ 
     { 
      "_id":"57b14b1831a5a2756fbc9873", 
      "description":"Request A", 
      "denied_requests":[] 
     }, 
     { 
      "_id":"57b14c2131a5a2756fbc9874", 
      "description":"Request B", 
      "denied_requests":[ ] 
     } 
] 

回答

1

運行下面的管道,它應該給你想要的結果:

var userId = "57a944390b1acf0d069388c1"; 
db.users.aggregate([ 
    { "$match": { "_id": userId } }, 
    { "$unwind": "$groups" }, 
    { 
     "$lookup": { 
      "from": "groups", 
      "localField": "groups.id", 
      "foreignField": "_id", 
      "as": "group" 
     } 
    }, 
    { "$unwind": "$group" }, 
    { 
     "$project": { 
      "requests": { 
       "$filter": { 
        "input": "$group.requests", 
        "as": "item", 
        "cond": { "$not": { 
         "$setIsSubset": [ 
          [userId], "$$item.denied_requests" 
         ] 
        } } 
       } 
      } 
     } 
    }, 
    { "$unwind": "$requests" }, 
    { 
     "$project": { 
      "_id": "$requests._id", 
      "description": "$requests.description", 
      "denied_requests": "$requests.denied_requests" 
     } 
    } 
]) 
+0

我嘗試這樣做,看起來沒有什麼後的第一個'$ lookup' – TheJediCowboy

+1

我剛剛意識到DB返回我當時的反感是<3.2,這意味着$ lookup不被支持,並且正在悄然失敗。 – TheJediCowboy

+0

https://github.com/facebook/react-native/issues/7626我相信涵蓋了這一點。 – TheJediCowboy