2017-10-13 93 views
0

我想根據整數字段中呈現的位數(它是嵌套屬性)從我的mongoDB中獲取記錄。由於mongoDB沒有函數來計算整數字段中顯示的位數,所以我使用下面的查詢來適應我的目的,但是我收到一個錯誤。基於整數值中的位數獲取MongoDB的記錄

db.collection.find({"Data.Integer_field": {$exists: true}, $where: function(){return toString("Data.Integer_field").length: {$gt:12}; } }).limit(2); 
+0

例如,爲什麼你不只是爲數字比較例如'Data.Integer_field:{$ gte:1000}'做數字比較? – JohnnyHK

+0

因爲它不包括數字爲00100的情況,因爲未將數據舍入爲零 –

+0

所以'Integer_field'是一個字符串? – JohnnyHK

回答

0

請嘗試以下解決方案:

db.collection.find({ 
    "Data.Integer_field" : {"$type" : 16} 
}).forEach(function(doc){ 
    if(doc.Data.Integer_field.toString().length > 12) { 
     print(doc); 
    } 
}); 

$類型是檢查數據類型(16是32位的整數)檢查Link

您可以使用$類型或$存在,對你來說什麼都是可行的。

而在這個例子中,我打印的結果,但你的工作方式。讓我知道事情的後續。

+0

這解決了問題謝謝 –

+0

太棒了!沒問題 –

1

您可以使用此腳本。

db.collection.find({ 
    "Data.Integer_field":{$exists: true}, 
    $where: function() { return ((new String(this.Data.Integer_field)).length > 12) ; } 
}).limit(2);