2011-12-20 26 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'。 请注意,它将适用于少量的数据。 –