开发者

MongoDB Group using Ruby driver

开发者 https://www.devze.com 2022-12-18 10:03 出处:网络
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:

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:

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} 
})

Results:

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

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.


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).

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号