2011-09-09 46 views
0

我使用Mongoid來獲取Mongo數據庫中某些類型的記錄的計數。當運行使用JavaScript方法查詢:用Ruby/Javascript查詢Mongo組中的計數結果的區別

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} 
] 

我誤解背後有什麼回事場景?我需要(可以嗎?)投這些計數,或者是隻顯示沒有.0的javascript結果嗎?

回答

2

JavaScript不區分浮動和整數。它有一個數字類型,實現爲雙精度型。因此,您在Ruby中看到的是正確的,mongo shell輸出遵循javascript打印約定,並顯示沒有小數部分而沒有'.0'的數字。'