在MongoDB中找到最接近坐标的条目

Find closest entries in MongoDB to coordinates

本文关键字:坐标 最接近 MongoDB      更新时间:2023-09-26

我很难找到最接近一组纬度/长度的项目。

我的对象的lat/lon是这样存储的:

 "address": "some_address",
    "city": "some_city",
    "coordinates": [
      32.214048,
      -84.361727
    ]

这是我目前使用的查询,当我使用它时,我没有得到任何结果,甚至不是一个空数组。

collection.find({coordinates: {$near: [40.296898, -111.694647] }, $maxDistance:100})

我如何查询我的对象来找到最近的对象?

你必须做三件事。

  1. 你必须保存你的坐标在[经度,纬度]顺序。这是mongo所要求的,你可以在文档中看到。因此,您的数据必须看起来像
    {
        "address": "some_address",
        "city": "some_city",
        "coordinates": [
          -84.361727,
          32.214048
        ]
    }
  • 一旦你有你的数据正确设置,你必须创建一个2dsphere索引,以便与geoNear工作。
        db.collection.createIndex({coordinates: "2dsphere"})
    
    那么你必须修正你的查询。这里需要传递一个带有几何属性的$nearSphere,这是你按照我们之前所说的顺序放置坐标的地方[经度,纬度]
  •     db.collection.find({ 
            coordinates: { 
                $nearSphere: { 
                    $geometry: { 
                        type: "Point", 
                        coordinates: [ -84.361727 , 32.214048 ] 
                    }, 
                    $maxDistance: 100 
                } 
            } 
        })