2013-08-06 121 views
0

我目前在Java Web應用程序中使用MongoDB的聚合框架,以根據其他用戶的偏好爲用戶生成推薦。在MongoDB聚合框架中獲取數組相交的大小

我正在使用的主要方法之一是查看數組交集。

現在我的算法只是考慮兩個用戶「相似」,如果他們有一個非零數組交集。

爲了建立一個更準確的算法,我想衡量集交集到我的聚合管道的大小。

有沒有辦法做到這一點?

+0

有趣的是,你是如何做非零陣列相交。在聚合框架? – drmirror

+0

你比較one_to_one用戶還是你需要one_to_many? – evilive

+0

您能否提供一些樣本文件以及您期望得到的結果? – Derick

回答

3

如果我理解你的問題,你有數據類似如下:

db.users.insert({_id: 100, likes: [ 
    'pina coladas', 
    'long walks on the beach', 
    'getting caught in the rain' 
]}) 
db.users.insert({_id: 101, likes: [ 
    'cheese', 
    'bowling', 
    'pina coladas' 
]}) 
db.users.insert({_id: 102, likes: [ 
    'pina coladas', 
    'long walks on the beach' 
]}) 
db.users.insert({_id: 103, likes: [ 
    'getting caught in the rain', 
    'bowling' 
]}) 
db.users.insert({_id: 104, likes: [ 
    'pina coladas', 
    'long walks on the beach', 
    'getting caught in the rain' 
]}) 

,並要計算給定用戶有多少匹配功能(「喜歡」在這個例子中),他們與其他用戶?下面聚集管道將實現這一點:

user = 100 
user_likes = db.users.findOne({_id: user}).likes 
return_only = 2 // number of matches to return 

db.users.aggregate([ 
    {$unwind: '$likes'}, 
    {$match: { 
     $and: [ 
      {_id: {$ne: user}}, 
      {likes: {$in: user_likes}} 
     ] 
    }}, 
    {$group: {_id: '$_id', common: {$sum: 1}}}, 
    {$sort: {common: -1}}, 
    {$limit: return_only} 
]) 

鑑於這將輸出上面的例子中輸入的數據顯示,前2場比賽結果如下:

{ 
    "result" : [ 
     { 
      "_id" : 104, 
      "common" : 3 
     }, 
     { 
      "_id" : 102, 
      "common" : 2 
     } 
    ], 
    "ok" : 1 
} 

注意,我假定你將只需要因爲可能會有非常多的用戶,因此排名如此之多。 $排序步驟緊跟$ limit步驟將完成此操作。如果不是這種情況,那麼你可以忽略流水線中的最後兩個步驟。

我希望這有助於!如果您還有其他問題,請告訴我。

布魯斯

1

由於MongoDB的2.6+,你可以使用$size表達。

如果您正在做兩個數組(集)的交集,您首先要使用$setIntersection運算符來查找這兩個集合的交集。另一個例子在this question中給出。

然後,您可以使用新的$size運算符來獲取管道交叉點輸出的大小。 This answer提供了一個使用新的$ size表達式的例子。