简体   繁体   中英

Sort Items in mongoDB using distance from a desired point

Database
MongoDB on Azure with Cosmos DB (so the Mongo version will be 3.6)

Scenario:
I wish to show to the user in a mobile app, the items are linked to a supplier which have coordinates deep in the document structure. I would like to display the items to the user in the app sorted by distance and show the distance (I do not wish to filter only the close ones).

Items Collection:

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

Suppliers Collection:

{
  "_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

The query should take in the coordinates of the end user and return the following:

{
  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
}

Thanks in advance

Actually you cannot query by location when your location is given as {"position": {lat: ##.######, lon: ##.##########}}

See GeoJSON Objects how MongoDB stores spatial data. When your location are given as GeoJSON then you can use Geospatial Queries , in your case it would be $nearSphere or $geoNear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM