2014-05-20 46 views
2

比方說,我有用戶的集合,每個用戶有他喜歡的頁面(想象一下Facebook頁面IDS)的數組:如何獲取流星中陣列相交的反應數據?

當前用戶:

{ 
    name: "me", 
    likes: [123,234,777] 
} 

目標列表:

{ 
    name: "Jane", 
    likes: [111,222,333] 
}, 
{ 
    name: "Mary", 
    likes: [567,234,777,654] 
}, 
{ 
    name: "John", 
    likes: [123,234,567,890,777] 
}, 
{ 
    name: "Steve", 
    likes: [666,777,321,432,543] 
}, 

結果:

{ 
    name: "John", 
    likes: [123,234,777] 
}, 
{ 
    name: "Mary", 
    likes: [234,777] 
}, 
{ 
    name: "Steve", 
    likes: [777] 
}, 
{ 
    name: "Jane", 
    likes: [] 
}, 

我想獲得被我最常見的用戶訂購的用戶的被動發佈。我需要反應,因爲每個用戶都有用戶在線 - 在線/離線。具有喜歡ID的數組是靜態的,但用戶在場狀態隨時間而變化。

+0

看看[這篇文章](https://www.discovermeteor.com/blog/reactive-joins-in-meteor/)關於被動連接。 –

回答

1

我會離開的發佈/訂閱和無功部分給你,但做一個集合交叉,而不必重複代碼的結果一般力學可以使用聚合框架,但需要執行。

值得注意的是,這僅僅是一個服務器側的功能,並且需要爲了在本調用.aggregate()方法來獲得到底層「節點本地驅動程序」的引用:

var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db; 

事實上MongoDB的2.6及以上有一個$setIntersection運營商可用,使這個簡單的:先

db.targets.aggregate([ 

    // You probably want a $match to find "friends" first 
    { "$match": { "_id": { "$in": [ friends ] } } }, 

    // Project the set intersection 
    { "$project": { 
     "name": 1, 
     "likes": { 
      "$setIntersection": [ "$likes", [123,234,777] ] 
     } 
    }} 
]) 

它仍然是與MongoDB的版本基本上可能到2.6,你只需要手動完成所有的工作,該$setIntersection運營商允許:

db.targets.aggregate([ 

    // You probably want a $match to find "friends" first 
    { "$match": { "_id": { "$in": [ friends ] } } }, 

    // Project an array with the matching values 
    { "$project": { 
     "name": 1, 
     "likes": 1, 
     "mylikes": { "$cond": [ 1, [123,234,777], 0 ] } 
    }}, 

    // Unwind both of the arrays 
    { "$unwind": "$likes" }, 
    { "$unwind": "$mylikes" }, 

    // Work out where those likes are the same. Intersection. 
    { "$project": { 
     "name": 1, 
     "likes": 1, 
     "match": { "$eq": [ "$likes", "$mylikes" ] } 
    }}, 

    // Filter the results that did not match 
    { "$match": { "match": true } }, 

    // Group back the array of likes 
    { "$group": { 
     "_id": "$_id", 
     "name": { "$first": "$name" }, 
     "likes": { "$push": "$likes" } 
    }} 
]) 

這最後一個消除了「珍妮」的條目,因爲沒有匹配的喜歡,但或多或​​少期望的結果。

如果你感興趣,那麼你應該看看this post,它涵蓋了更詳細地使用與流星聚合。但一般的方法在這裏,並且應該提供比在客戶端中處理結果以找到集合的交集更加快速和更優雅的解決方案。