簡體   English   中英

在mongoose中查找自定義條件

[英]Find with custom condition in mongoose

我正在開發一個node.js web-app,我正在使用mongoose和MongoDB進行存儲。 這是一個gelocation應用程序。 所以有時我必須找到存儲在數據庫中的10個最近的地方。 我有這種方法來計算這個距離:

 var haversine = function(p1, p2) {
var R = 6371; // km
var dLat = toRad(p2.lat-p1.lat);
var dLon = toRad(p2.lon-p1.lon);
var lat1 = toRad(p1.lat);
var lat2 = toRad(p2.lat);

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

return d;
 }

其中p1和p2是點{lat:Integer,lon:Integer}。

那么,我該怎么做才能找到最近的地方?

如果我不理解這個問題,請道歉,但如果你已經在MongoDB中存儲了lat和lon,為什么不只是確保該鍵上的Geo索引並使用MongoDB本身來查找最近的點。

假設由lat和lon組成的location鍵上的Geo索引,您可以簡單地發出類似於以下內容的內容:

db.places.find( { location : { $near : [lon,lat] } } ).limit(10)

哪個應該找到數據庫中最近的十個位置到lon,lat定義的位置。

您可以在地理空間索引的文檔中找到更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM