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'。 請注意,它將適用於少量的數據。 –