【问题标题】:Correct Mongodb query equivalent of SQL query正确的 MongoDB 查询等效于 SQL 查询
【发布时间】:2019-06-21 07:26:35
【问题描述】:

在 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 + NodeJs。

谢谢大家。

【问题讨论】:

    标签: node.js mongodb-query


    【解决方案1】:

    好的,我设法做到了:

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

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

    Mongoose 连接(特别提到“useCreateIndex: true”):

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

    Mongoose 架构:

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多