开发者

Difference with count result in Mongo group by query with Ruby/Javascript

I'm using Mongoid to get a count of certain types of records in a Mongo database. When running the quer开发者_运维技巧y with the javascript method:

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

I get the following results:

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

Does exactly what I want it to do. However, when I utilize the corresponding Mongoid code to perform the same query:

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

the count parameters are (seemingly) selected as floats instead of integers:

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

Am I misunderstanding what's going on behind the scenes? Do I need to (can I?) cast those counts or is the javascript result just showing it without the .0?


JavaScript doesn't distinguish between floats and ints. It has one Number type that is implemented as a double. So what you are seeing in Ruby is correct, the mongo shell output follows javascript printing conventions and displays Numbers that don't have a decimal component without the '.0'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜