首页 > 解决方案 > 使用与所需点的距离对 mongoDB 中的项目进行排序

问题描述

Azure 上的数据库
MongoDB 与 Cosmos DB(因此 Mongo 版本将是 3.6)

场景:
我希望在移动应用程序中向用户展示,这些项目链接到在文档结构深处具有坐标的供应商。我想在应用程序中按距离排序向用户显示项目并显示距离(我不希望只过滤接近的项目)。

物品收藏:

{
  "_id": {"$oid": "########################"},
  "name": "items 1",
  "supplierId": {"$oid": "########################"},
  "others fields": etc.
},{
  "_id": {"$oid": "########################"},
  "name": "items 2",
  "supplierId": {"$oid": "########################"},
  "others fields": etc.
}, etc

供应商集合:

{
  "_id": {"$oid": "########################"},
  "name": "Supplier A",
  "Address": {"position": {lat: ##.######, lon: ##.##########}},
  "others fields": etc.
},{
  "_id": {"$oid": "########################"},
  "name": "Supplier B",
  "Address": {"position": {lat: ##.######, lon: ##.##########}},
  "others fields": etc.
}, etc

查询应采用最终用户的坐标并返回以下内容:

{
  Item: "Item 1",
  Supplier: "Supplier A",
  DistanceInKm: 1.7
},{
  Item: "Item 2",
  Supplier: "Supplier A",
  DistanceInKm: 1.7
},{
  Item: "Item 3",
  Supplier: "Supplier B",
  DistanceInKm: 3.2
},{
  Item: "Item 4",
  Supplier: "Supplier C",
  DistanceInKm: 4.4
},{
  Item: "Item 5",
  Supplier: "Supplier C",
  DistanceInKm: 4.4
}

提前致谢

标签: mongodbgeospatialmongodb-geospatial

解决方案


实际上,当您的位置为{"position": {lat: ##.######, lon: ##.##########}}

请参阅GeoJSON 对象MongoDB 如何存储空间数据。当您的位置以 GeoJSON 的形式给出时,您可以使用Geospatial Queries,在您的情况下它会是$nearSphere$geoNear


推荐阅读