mongodb - 使用与所需点的距离对 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
}
提前致谢
解决方案
实际上,当您的位置为{"position": {lat: ##.######, lon: ##.##########}}
请参阅GeoJSON 对象MongoDB 如何存储空间数据。当您的位置以 GeoJSON 的形式给出时,您可以使用Geospatial Queries,在您的情况下它会是$nearSphere
或$geoNear
推荐阅读
- python - 如何将绘图、选项卡和图像导出到单个 html 中
- java - 使用 Lombok Builder 进行多个插入
- flutter - 将数据第二个打开的对话框发送到第一个打开的对话框
- mysql - 根据字段值对mysql数据进行排序
- dart - 如何等待 Dart 中异步下载的完成或错误?
- performance - 直到列表为空的while循环的时间复杂度?
- c++ - Boost库静态链接
- php - PHP循环遍历数组并将值设置为变量并添加到html表
- flutter - Flutter 内容在 modal_bottom_sheet 上间歇性地被剪辑
- powerbi - 如何计算 Power BI 中时间列中接收数据的频率?