Mongo Group函数调用Ruby

时间:2014-03-26 05:36:07

标签: ruby mongodb-ruby

我有一个像这样的mongodb集合

{" assigneeId" => 1000," status" => 3," starttime" => " 2014年2月25日"," numofdays => 6} {" assigneeId" => 1000," status" => 2," starttime" => " 2014年1月10日"," numofdays => 6} {" assigneeId" => 1000," status" => 3," starttime" => " 2014年1月1日"," numofdays => 20}

我编写了一个MongoDB查询,将上述集合与状态为3的assigneeId分组,并添加像这样的numofdays值

db.events.group({key:{assigneeId:1},cond:{status:{$ gte:3}},reduce:function(curr,result){result.total ++; result.numofdays + = curr .nu​​mofdays;},initial:{total:0,numofdays:0}})

这给出了Mongodb cli预期的输出。

当我编写用于执行相同查询的ruby代码时,我无法使其工作。我遇到了类似问题的不同命中,但这些格式似乎都不起作用。我无法通过ruby中的语法错误来进行分组功能。请注意我不使用mongoid。如果我可以使用Aggregation框架来完成这项工作,那对我来说也没问题。

这是我写的ruby查询和同样的错误。

@events_h.group (
                :cond => {:status => { '$in' => ['3']}},
                :key => 'assigneeId',
                :initial => {count:0},
                :reduce => "function(x, y) {y.count += x.count;}"
                )

我收到错误

analyze.rb:43:语法错误,意外',',期待')'                 out = @ events_h.group([" assigneeId"],{},{}," function(){}")                                                       ^ analyze.rb:43:语法错误,意外')',期待keyword_end analyze.rb:83:语法错误,意外的输入结束,期待keyword_end

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:0)

以下测试包括使用方法,组和聚合的解决方案。 我建议您使用聚合,它更快,避免使用JavaScript并使用V8引擎。 希望这会有所帮助。

test.rb

require 'mongo'
require 'test/unit'

class MyTest < Test::Unit::TestCase
  def setup
    @events_h = Mongo::MongoClient.new['test']['events_h']
    @docs = [
        {"assigneeId" => 1000, "status" => 3, "starttime" => "2014 Feb 25", "numofdays" => 6},
        {"assigneeId" => 1000, "status" => 2, "starttime" => "2014 Jan 10", "numofdays" => 6},
        {"assigneeId" => 1000, "status" => 3, "starttime" => "2014 Jan 1", "numofdays" => 20}]
    @events_h.remove
    @events_h.insert(@docs)
  end

  test "group" do
    result = @events_h.group(
        :cond => {:status => {'$in' => [3]}},
        :key => 'assigneeId',
        :initial => {numofdays: 0},
        :reduce => "function(x, y) {y.numofdays += x.numofdays;}"
    )
    assert_equal(26, result.first['numofdays'])
    puts "group: #{result.inspect}"
  end

  test "aggregate" do
    result = @events_h.aggregate([
        {'$match' => {:status => {'$in' => [3]}}},
        {'$group' => {'_id' => '$status', 'numofdays' => {'$sum' => '$numofdays'}}}
    ])
    assert_equal(26, result.first['numofdays'])
    puts "aggregate: #{result.inspect}"
  end
end

$ ruby​​ test.rb

Loaded suite test
Started
aggregate: [{"_id"=>3, "numofdays"=>26}]
.group: [{"assigneeId"=>1000.0, "numofdays"=>26.0}]
.

Finished in 0.010575 seconds.

2 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed

189.13 tests/s, 189.13 assertions/s