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