MongoDB Group Uses Ruby Driver

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.

+4
source share
1 answer

This is a rather strange behavior. I just ran your code locally and it worked. Can you check if you are using driver version 0.18.2? If so, make sure that a single version is installed (exactly the same as a health check).

I don’t think this should have any meaning, but I didn’t run the #group from MongoMapper - I used only stone. You can try it too. Here is 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) 
+2
source

Source: https://habr.com/ru/post/1299247/


All Articles