简体   繁体   English

在mongoose中查找自定义条件

[英]Find with custom condition in mongoose

I'm developing a node.js web-app where I'm using mongoose and MongoDB for storage. 我正在开发一个node.js web-app,我正在使用mongoose和MongoDB进行存储。 It's a gelocation app. 这是一个gelocation应用程序。 so sometimes I have to find the 10 nearest places stored in database. 所以有时我必须找到存储在数据库中的10个最近的地方。 I have this method to calculate this distance: 我有这种方法来计算这个距离:

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

where p1 and p2 are points {lat: Integer, lon: Integer}. 其中p1和p2是点{lat:Integer,lon:Integer}。

So, How should I do to find the nearest places? 那么,我该怎么做才能找到最近的地方?

Apologies if I am not understanding the question, but if you have a lat and lon stored in MongoDB already, why not just ensure a Geo index on that key and use MongoDB itself to find the nearest points. 如果我不理解这个问题,请道歉,但如果你已经在MongoDB中存储了lat和lon,为什么不只是确保该键上的Geo索引并使用MongoDB本身来查找最近的点。

Assuming a Geo index on location key consisting of lat and lon, you can simply issue something similar to the following: 假设由lat和lon组成的location键上的Geo索引,您可以简单地发出类似于以下内容的内容:

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

Which should find the nearest ten places in your database to the location defined at lon,lat. 哪个应该找到数据库中最近的十个位置到lon,lat定义的位置。

You can find more information at the documentation for geospatial indexing. 您可以在地理空间索引的文档中找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM