2012-11-07 50 views

回答

17

有趣的問題。我不知道你是否能在單個查詢做到這一點,但你可以在兩個做到這一點:

var x = 1; // given integer 
closestBelow = db.test.find({ratio: {$lte: x}}).sort({ratio: -1}).limit(1); 
closestAbove = db.test.find({ratio: {$gt: x}}).sort({ratio: 1}).limit(1); 

然後你只檢查其中兩個文檔的擁有ratio最接近目標整數。

MongoDB的3.2更新

的3.2版本增加了對$abs絕對值匯聚運營商現在允許這種在一個單一的aggregate查詢進行支持:

var x = 1; 
db.test.aggregate([ 
    // Project a diff field that's the absolute difference along with the original doc. 
    {$project: {diff: {$abs: {$subtract: [x, '$ratio']}}, doc: '$$ROOT'}}, 
    // Order the docs by diff 
    {$sort: {diff: 1}}, 
    // Take the first one 
    {$limit: 1} 
]) 
5

我有另一個想法,但非常棘手,需要改變你的數據結構。

可以使用geolocation index它通過MongoDB的支持

首先,你的數據更改爲這種結構,並保持第二值0

{'ratio':[1.437, 0]} 

然後你可以使用$near運營商找到最接近的比值,並且由於運算符使用您給出的整數返回按距離排序的列表,所以必須使用limit才能得到最接近的值。

db.places.find({ ratio : { $near : [50,0] } }).limit(1) 

如果你不想這樣做,我認爲你可以僅使用@ JohnnyHK的答案:)

+0

我曾經考慮過申請地理位置這樣......我想我會把這一槍。比例值實際上是圖像的縱橫比,所以我可以將widthxheight作爲尺寸查詢。 – DeaconDesperado

相關問題