【问题标题】:MongoDB sort document based on latitude and longitudeMongoDB根据经纬度对文档进行排序
【发布时间】:2021-10-22 19:46:58
【问题描述】:

我正在尝试创建一个 根据纬度和经度对文档进行排序的 mongoDB 查询。所以最近的将首先出现。我在 mongoDB 中有以下地理定位模型结构。

"place" : {
    "latitude" : "22.4856889",
    "longitude" : "70.0614146"
},
"address" : "Main Street",
...
...

所以我必须根据内部对象的纬度和经度进行排序。任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 你不能把纬度和经度当作数字,然后$sort。有没有我忽略的特殊情况?
  • 如果您正在查看按距特定点的距离排序,您可以查看answer
  • 我从特定的角度来看。您标记的答案是具有不同的模型结构。你能帮忙看看我的模型结构吗?
  • 让我在本地运行一些查询并回复您。我的 mongo 有点生锈了 rn
  • 我添加了新问题。你能检查一下吗? stackoverflow.com/questions/68896501/…

标签: mongodb mongoose aggregation-framework aggregate aggregation


【解决方案1】:

为了使用near,模型结构应该是这样的(GeoJSON):

{
    "_id" : ObjectId("61224d9e52d4af7999de80af"),
    "location" : {
        "type" : "Point",
        "coordinates" : [ 
            -73.88, 
            40.78
        ]
    },
    "name" : "La Guardia Airport",
    "address" : "Main Street"
}

你必须在集合中创建索引:

db.collection.createIndex( { location : "2dsphere" } )

然后,通过 geoNear 找到最近的文档(也可以计算距离):

db.collection.aggregate([
  {
    $geoNear: {
      near: {
        type: "Point",
        coordinates: [
          -73.98142,
          40.71782
        ]
      },
      key: "location",
      distanceField: "dist.calculated",
      query: {}
    }
  }
])

【讨论】:

  • 谢谢。这将只给出最近的位置或所有最近的文件?
  • 这将给出所有最近的文档,您可以在聚合末尾使用$limit以仅获取最近的。
  • 非常感谢。我将在我的应用程序中测试一次并接受答案。
  • 我添加了新问题。你能检查一下吗? stackoverflow.com/questions/68896501/…
【解决方案2】:

使用$near操作自动以最近点排序 https://docs.mongodb.com/manual/reference/operator/query/near/

【讨论】:

  • 谢谢,但是如何根据我的模型结构实现查询?
  • 你能把你的数据改成 {place:[22.22222,30.33333],address:"etc."} 吗?
  • 谢谢。我必须更改它以使其根据我的需要工作
  • 我添加了新问题。你能检查一下吗? stackoverflow.com/questions/68896501/…
  • 请立即查看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
相关资源
最近更新 更多