本文介绍了如何使用MongoDB Ruby Driver来执行“Group” (通过...分组)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与使用Ruby驱动程序的相关
如果我想在SQL中执行以下操作:
select page_id,count(page_id) from a_table group by page_id
我以为MongoDB的文档是这样说的:
db.pageviews.group(
{
key:{'user.agent':true},
initial:{sum:0},
reduce:function(doc,prev){prev.sum + = 1}
});
但它不在另一个计算器中。
更新:实际上,在上面的链接中,解决方案就像
Analytic.collection .group(['page_id'],nil,
{:count => 0},function(x,y){y.count ++})
的作品,但只是想知道为什么这篇文章的第一个方法不起作用。解决方案
我最终通过
Analytic.collection.group(['myapp_id' ],{:page =>'products'},
{:pageviews => 0,:timeOnPage => 0},
function(x,y){y.pageviews + = x.pageviews; y.timeOnPage + = x.timeOnPage})
然后我用Map /之后减少,因为Map / Reduce似乎是一个更通用和更强大的方法。
related to MongoDB Group using Ruby driver
if I want to do something like the following in SQL:
select page_id, count(page_id) from a_table group by page_id
I thought the MongoDB's doc says
http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method
group(key, condition, initial, reduce, finalize = nil)
# returns an array
So from the other post, I am using:
Analytic.collection.group( "fucntion (x) return {page_id : x.page_id}",
nil,
{:count => 0},
"function(x, y) { y.count++ }" )
but it actually returns
[{"count"=>47.0}]
which is the total number of records (documents) in the collection. Is something not correct above? I thought the key might be a static string like in
http://kylebanker.com/blog/2009/11/mongodb-count-group/
db.pageviews.group(
{
key: {'user.agent': true},
initial: {sum: 0},
reduce: function(doc, prev) { prev.sum += 1}
});
but it is not in the other stackoverflow post.
Update: actually, in the link above, the solution like
Analytic.collection.group( ['page_id'], nil,
{:count => 0}, "function(x, y) { y.count++ }" )
works, but just wonder why the first method in this post didn't work.
解决方案
I finally got it to work by
Analytic.collection.group( ['myapp_id'], {:page => 'products'},
{:pageviews => 0, :timeOnPage => 0},
"function(x, y) { y.pageviews += x.pageviews; y.timeOnPage += x.timeOnPage }" )
but then I used Map/Reduce afterwards as Map/Reduce seems like a more generic and powerful method.
这篇关于如何使用MongoDB Ruby Driver来执行“Group” (通过...分组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!