正确的Mongodb查询等效于SQL查询

时间:2019-06-21 07:26:35

标签: node.js mongodb-query

在Mongodb + Nodejs中进行此确切的SQL查询的正确方法是什么?

select *,
    acos(cos(centerLat * (PI()/180)) *
     cos(centerLon * (PI()/180)) *
     cos(lat * (PI()/180)) *
     cos(lon * (PI()/180))
     +
     cos(centerLat * (PI()/180)) *
     sin(centerLon * (PI()/180)) *
     cos(lat * (PI()/180)) *
     sin(lon * (PI()/180))
     +
     sin(centerLat * (PI()/180)) *
     sin(lat * (PI()/180))
    ) * 3959 as Dist
from TABLE_NAME
having Dist < radius
order by Dist

从此请求中获取的代码: https://stackoverflow.com/a/12235184/8025329

这是我的猫鼬模式:

const spotSchema = new Schema({
    latitude: { type: String, required: true },
    longitude: { type: String, required: true },
    spotDate: { type: Date, required: true }
});

我希望检索记录,显示在用户位置附近的地图上的点。我认为该部分与公式+ sql查询无关。我的问题是如何将其转换为Mongodb + NodeJ。

感谢所有人。

1 个答案:

答案 0 :(得分:0)

好吧,我设法做到了:

我从这个答案中得到了宝贵的指导: https://stackoverflow.com/a/23291154/8025329

最终这使它起作用(不是最终的,也不是完善的,但是解决了主要的挑战),我发布了最重要的部分:

猫鼬连接(对“ useCreateIndex:true”的特别提及):

mongoose.connect(config.MONGO_URI, { useNewUrlParser: true, useCreateIndex: true });

猫鼬模式:

const Schema = new Schema({
    loc: { type: Object, index: '2dsphere', required: true },
    category: { type: String, required: true }
});

GeoJson对象示例:

{
loc : { type: "Point", coordinates: [ longitude, latitude ] },
        category : "location"
      }

查找附近的地方:

MongodbSchema.aggregate([
      {
        $geoNear: {
           near: { type: "Point", coordinates: [ longitude , latitude ] },
           key: "loc",
           distanceField: "dist.calculated",
           maxDistance: 600,
           query: { category: "location" },
           num: 100,
           spherical: true
        }
      }
   ], function(err, locations){
    if (err) throw err;

    res.send(locations);

   });

有用的链接: https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear

https://docs.mongodb.com/manual/reference/geojson/

相关问题