2017-04-22 230 views
-1

我正在使用nodejs和mongodb。 我想搜索一個數字範圍內的文檔,但該函數總是給我在範圍之外的數字。例如,這是我的功能,我想,他們有一個字段的大小與1之間的數字到1200的文檔的結果:MongoDB範圍問題

db.collection(example).find({ 
    size: { 
    "$gte": 1, 
    "$lte": 1200 
    } 
}).toArray(function(err, results) { 
    db.close(); 
    console.log("results=" + results); 
}); 

在數據庫中的文檔:

{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d2"), "size" : -1 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d3"), "size" : 100 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d4"), "size" : 800 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d5"), "size" : 1999 } 

查詢的結果應該是:

{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d3"), "size" : 100 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d4"), "size" : 800 } 

但查詢的結果是:

{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d2"), "size" : -1 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d3"), "size" : 100 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d4"), "size" : 800 } 
{ "_id" : ObjectId("56659a492b9eaad2d9e6d4d5"), "size" : 1999 } 
+0

我按照你想要的方式編輯了 – RandomGuy17

+0

你在示例文檔中有'_id'值的重複,但修復後,當我嘗試查詢時,它工作正常。 – JohnnyHK

+0

這是實際的數據嗎? Ids是重複的 –

回答

2

我相信你需要在你的尺寸條件下使用$和子句。它可能看起來像這樣:

db.collection(example).find({ 
    $and: [ 
    { size: { $gte: 1 } }, 
    { size: { $lte: 1200 } } 
    ] }).toarray... 

請參閱mongo文檔中的示例here

編輯:其實,一個隱含的,很好。如上所述,這裏的實際問題是大小值被存儲爲字符串,而不是整數。

+0

@ RandomGuy17您不需要使用'$和',所以如果問題實際上是文檔中的size值是字符串,那麼未來的用戶將會誤導這一點。 – JohnnyHK