2011-12-20 24 views
0

讓我們說我們有posts表這樣如何通過集團在MongoDB中與本案

id | friend_id | title | 
- - | - - - - - - | - - - - | 
1 |  2  | John | 
2 |  5  | John | 
3 |  4  | John | 
4 |  4  | Joe  | 
5 |  5  | Amy  | 
6 |  2  | Amy  | 
7 |  2  | Joe  | 

我想要一個查詢,將GROUP BY title行和返回一行與friend_id的數組。

結果可能是某事像那:

{ 
    John: { id: 1, title: John, friend_id: [2,5,4] } 
    Joe: { id: 4, title: Joe, friend_id: [4,2] } 
    Amy: { id: 5, title: Amy, friend_id: [5,2] } 
} 

我知道上面的例子不是一個真正的一個!只是有道理。

回答

0

你可以用mongodb做這個pivoting使用map reduce。 The MongoDB Cookbook中有一個很好的例子。請看一下。它不那麼難,你可以自己做。

1

這個查詢

db.posts.group(
    key: {title: true} 
    , initial: {friend_ids : []} 
    , reduce: function(doc, out){ out.push(doc.friend_id) } 
    }); 

會返回結果一樣

{ 
[{title : "John", friend_ids : [2,5,4]} , ....] 
} 
+0

這裏是我試圖得到它使用Ruby'Post.collection.group工作({鍵:[ 「標題」], initial:{friend_ids:[]},reduce:「function(doc,out){out.push(doc.friend_id)}」})'但是它返回錯誤:'Mongo :: OperationFailure:Database command'group'failed: (errmsg:'exception:reduce invoke failed:JS Error:TypeError:out.push is a function reduce setup:1'; code:'9010'; ok:'0.0')。' – amrnt

+0

reduce func它應該看起來像這樣:'function(doc,out){out.friend_ids.push(doc.friend_id)}' 原始答案中缺少'friend_ids'。 請注意,它將適用於少量的數據。 –