Ruby中的Mongo Group函数调用



我有一个像这样的mongodb集合

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

我编写了一个MongoDB查询,将上述集合与状态为3的assignneeid分组,并添加nummofdays的值,如下所示

db.events。group ({key: {assignneeid:1}, cond: {status: {$gte: 3}}, reduce: function (curr, result) {result.total++;结果。{, initial: {total:0, nummofdays:0}})

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

当我为执行相同的查询编写ruby代码时,我无法使其工作。我得到了很多不同的打击类似的问题,但没有格式似乎工作。我无法越过ruby中分组函数的语法错误。请注意,我没有使用mongoid。如果我能得到这个工作与聚合框架,这对我来说也很好。

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

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

Error I am get

分析。语法错误,`,`,`)`Out = @events_h。集团([" assigneeId "], { }, { }, " function(){}")^分析。语法错误,意外的')',期望keyword_end分析。Rb:83:语法错误,意想不到的end- input,期望keyword_end

任何帮助都非常感谢。

谢谢

下面的测试包括同时使用group和aggregate两种方法的解决方案。我建议您使用聚合,它更快,避免使用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

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

相关内容

  • 没有找到相关文章

最新更新