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] }
}
我知道上面的例子不是一个真正的一个!只是有道理。
这里是我试图得到它使用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
reduce func它应该看起来像这样:'function(doc,out){out.friend_ids.push(doc.friend_id)}' 原始答案中缺少'friend_ids'。 请注意,它将适用于少量的数据。 –