I am trying to return a list of year / month combinations with counts to describe blog posts. The idea is that they will be displayed as follows:
- January 2010 (1 post)
- December 2009 (2 posts)
- ...
I managed to get this to work using the MongoDB JS shell, and it returns the 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 need. However, trying to convert this to code suitable for the ruby ββdriver, I cannot get it to work. I looked through the documentation and, in my opinion, the following should give the same results (I use MongoMapper, hence 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 returning a good array of useful data, I get this mess:
{ "function(x) { return { month: x.datetime.getMonth(), year:x.datetime.getFullYear() }; }" => nil, "count" => 4.0 }
It seems that either he completely ignores his own documentation (and my understanding of the source code!), Or I'm missing something fundamental here. I almost pull out my hair, any help is gratefully accepted.