如何使用geoNear查询MongoDB?

时间:2019-09-13 16:43:00

标签: node.js mongodb express mongoose

我正在尝试使用mongodb使用聚合函数geoNear和near来根据经度和纬度定位距离。

`router.get('/devops' , (req,res,next) => {
   /*
   Devops.find({})
   .then((alldevops) => {
      res.send(alldevops);
   })
   */
  Devops.aggregate().near({
   near: [parseFloat(req.query.lng), parseFloat(req.query.lat)],
   maxDistance: 100000,
   spherical: true,
   distanceField: "dist.calculated"
  }).then((alldevops)=>{
     res.send(alldevops);
  });

});`

我收到一条错误消息

  

MongoError:查询GeoJSON点时,geo near仅接受一个参数。找到额外的字段:$ max距离:100000.0

1 个答案:

答案 0 :(得分:0)

第一件事是您的架构应类似于下面指定的jeo.json格式

{
  "other_key":"other_key_type"

 // this is important
  "geometry": {
    "type": "Point",
    "coordinates": [Number] // it is [latitude, longitude], yes it is reverse way
  }

}

现在,您有了使用该架构的架构将数据插入数据库中

现在,您可以通过以下示例在数据上应用地理附近概念

YourModal.aggregate([
    {
      $geoNear: {
        near: { type: 'Point', coordinates: [16.51194, 80.735627] },
        distanceField: 'dist.calculated',
        includeLocs: 'dist.location',
        spherical: true
      }
    },
    {
      $project: {
        dist: 1
      }
    }
  ])

在这里您将获得许多选择,但我已从给定坐标中提取了唯一的距离。 我认为这将为从数据库实现geoNear查询提供一个简短的思路