使用Ruby驱动程序的MongoDB Group [英] MongoDB Group using Ruby driver

查看:79
本文介绍了使用Ruby驱动程序的MongoDB Group的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试带回年份/月份组合列表,其中包含用于描述博客文章的计数.想法是它们将像这样显示:

I'm trying to bring back a list of year/month combinations with counts for describing blog posts. The idea is that they will be displayed like so:

  • 2010年1月(1个帖子)
  • 2009年12月(2个帖子)
  • ...

我设法使用MongoDB JS Shell使其工作,并且它以有用的格式返回结果:

I have managed to get this to work using the MongoDB JS shell, and it returns results in a useful format:

db.posts.group({ 
    keyf: function(x){ 
                      return { 
                              month: x.datetime.getMonth(), 
                              year:x.datetime.getFullYear() 
                      }; 
    }, 
    reduce: function(x,y){ y.count++ }, 
    initial:{count:0} 
})

结果:

[ { "month" : 0, "year" : 2010, "count" : 3 },
  { "month" : 0, "year" : 1970, "count" : 1 } ]

这太好了,正是我所追求的.但是,尝试将其转换为适用于ruby驱动程序的代码,我无法使其正常工作.我看了一下文档,据我所知,以下内容应该会产生相同的结果(我使用的是MongoMapper,因此是Post.collection):

This is great, exactly what I'm after. However, trying to convert this into code appropriate for the ruby driver, I can't get it to work. I have looked at the documentation and from my understanding, the following should yield the same results (I'm using MongoMapper, hence the Post.collection):

@archive = Post.collection.group(
  "function(x) { return { month: x.datetime.getMonth(), year:x.datetime.getFullYear() }; }",
  nil, { :count => 0 }, 'function(x,y){y.count++}', true)

我没有得到很多有用的数据,而是弄得一团糟:

Instead of giving back the nice array of useful data, I'm getting this mess:

{
  "function(x) { return { month: x.datetime.getMonth(), year:x.datetime.getFullYear() }; }" => nil, 
  "count" => 4.0
}

似乎是完全违反了自己的文档(以及我对源代码的理解!),或者我在这里缺少了一些基本的知识.我几乎要拔头发了,感激地接受了任何帮助.

It seems that either it is completely defying its own documentation (and my understanding of the source code!) or I am missing something fundamental here. I'm almost pulling my hair out, any help gratefully accepted.

推荐答案

这是非常奇怪的行为.我只是在本地运行您的代码,一切正常.您可以验证使用的驱动程序版本为0.18.2吗?如果是这样,请确保这是安装的唯一版本(只是进行完整性检查).

That's pretty strange behavior. I just ran your code locally, and everything worked. Can you verify that you're using the driver version 0.18.2? If so, make sure that that's the only version installed (just as a sanity check).

我认为这没什么用,但是我不是从MongoMapper运行#group的-我只是在使用gem.您也可以尝试.这是我运行的代码:

I don't think it should make any difference, but I wasn't running #group from MongoMapper -- I was using the gem alone. You might try that, too. Here's the code I ran:

require 'rubygems'
require 'mongo'

d = Mongo::Connection.new.db('blog')
c = d['post']

p c.group("function(x) { return { month: x.date.getMonth(), year:x.date.getFullYear() }; }", 
  nil, 
  { :count => 0 }, 
  "function(x,y){y.count++}", 
  true)

这篇关于使用Ruby驱动程序的MongoDB Group的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆