如何在mongoose和nodejs中使用$ geoNear

时间:2022-09-25 16:27:30

I am trying to display distance between two coordinates. Below query executes and gives result as expected

我试图显示两个坐标之间的距离。下面的查询执行并按预期给出结果

db.runCommand( { geoNear: "distances",
             near: [ 83.307974, 17.716456],
             spherical: true
           }  );

I would like to execute this query from nodejs script. I am using mongoose. I tried aggregate function yet i failed to obtain the result. Can someone guide me in correct path!

我想从nodejs脚本执行此查询。我正在使用猫鼬。我尝试了聚合功能,但我没有获得结果。有人可以指导我走正确的道路!

I tried this:

我试过这个:

 db.getCollection('distances').aggregate([
  { 
        "$geoNear": {
            "near": {
                 "type": "Point",
                 "locc": [83.307974, 17.716456]
             },
             "distanceField": "distance",

             "spherical": true

         }
    }
]);

References:

geoNear * question
geoNeam MongoDB

geoNear *问题geoNeam MongoDB

1 个解决方案

#1


Try changing "locc" to "coordinates" and also ensure you have created either a 2d or 2dsphere index for the collection that contains the coordinates.

尝试将“locc”更改为“coordinates”,并确保为包含坐标的集合创建了2d或2dsphere索引。

db.getCollection('distances').aggregate([
  { 
        "$geoNear": {
            "near": {
                 "type": "Point",
                 "coordinates": [83.307974, 17.716456]
             },
             "distanceField": "distance",

             "spherical": true

         }
    }
]);

#1


Try changing "locc" to "coordinates" and also ensure you have created either a 2d or 2dsphere index for the collection that contains the coordinates.

尝试将“locc”更改为“coordinates”,并确保为包含坐标的集合创建了2d或2dsphere索引。

db.getCollection('distances').aggregate([
  { 
        "$geoNear": {
            "near": {
                 "type": "Point",
                 "coordinates": [83.307974, 17.716456]
             },
             "distanceField": "distance",

             "spherical": true

         }
    }
]);