mongodb group using ruby driver

mongodb group using ruby driver  using -'ruby,mongodb'

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:

January 2010 (1 post)
December 2009 (2 posts)

I have managed to get this to work using the MongoDB JS shell, and it returns results in a useful format:{
    keyf: function(x){
                      return {
                              month: x.datetime.getMonth(),
    reduce: function(x,y){ y.count++ },


[ { "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 =
  "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.

asked Oct 7, 2015 by deepak gupta
0 votes

1 Answer

0 votes

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 ='blog')
c = d['post']

p"function(x) { return { month:, }; }", 
  { :count => 0 }, 
answered Oct 7, 2015 by param.oncemore