【问题标题】:Difference with count result in Mongo group by query with Ruby/Javascript使用 Ruby/Javascript 查询 Mongo 组中计数结果的差异
【发布时间】:2011-09-09 00:25:36
【问题描述】:

我正在使用 Mongoid 来获取 Mongo 数据库中某些类型记录的计数。使用 javascript 方法运行查询时:

db.tags.group({
    cond : { tag: {$ne:'donotwant'} },
    key: { tag: true },
    reduce: function(doc, out) { out.count += 1; },
    initial: { count: 0 }
});

我得到以下结果:

[
{"tag" : "thing", "count" : 4},
{"tag" : "something", "count" : 1},
{"tag" : "test", "count" : 1}
]

完全符合我的要求。但是,当我使用相应的 Mongoid 代码执行相同的查询时:

Tag.collection.group(
    :cond    => {:tag => {:$ne => 'donotwant'}},
    :key     => [:tag],
    :reduce  =>  "function(doc, out) { out.count += 1 }",
    :initial => { :count => 0 },
)

计数参数(似乎)被选择为浮点数而不是整数:

[
{"tag"=>"thing", "count"=>4.0},
{"tag"=>"something", "count"=>1.0},
{"tag"=>"test", "count"=>1.0}
]

我是否误解了幕后发生的事情?我需要(我可以吗?)转换这些计数还是 javascript 结果只是在没有 .0 的情况下显示它?

【问题讨论】:

    标签: ruby mongodb mongoid


    【解决方案1】:

    JavaScript 不区分浮点数和整数。它有一个实现为双精度的数字类型。因此,您在 Ruby 中看到的内容是正确的,mongo shell 输出遵循 javascript 打印约定并显示没有“.0”的没有小数部分的数字

    【讨论】:

      猜你喜欢
      • 2015-10-25
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2011-03-01
      • 1970-01-01
      相关资源
      最近更新 更多