Geo location search

Hi!

I have one document and I want to attach multiple locations (lat/lng pairs) into it to easily search It afterwards.
Does anyone know a good way to achieve this?

{
title: 'Test title’
locations: [
{ lat: 48.210033,
lng: 16.363449
},
{ lat: 48.210033,
lng: 16.363449
},
{ lat: 48.210033,
lng: 16.363449
},
{ lat: 48.210033,
lng: 16.363449
},
]

Thank you so much!

Do you want to be able to search by distance? Or just by simple match?

well by distance would be great

Have a read of the MongoDB docs for geospatial data and queries:
https://docs.mongodb.com/manual/geospatial-queries/#geo-overview-location-data

Key things are that you’ll need to store each location as GeoJSON. Either as a list of individual points:

{
      type: "Point",
      coordinates: [-73.856077, 40.848447]
}

Or as a single MultiPoint geometry:

{
  type: "MultiPoint",
  coordinates: [
     [ -73.9580, 40.8003 ],
     [ -73.9498, 40.7968 ],
     [ -73.9737, 40.7648 ],
     [ -73.9814, 40.7681 ]
  ]
}

Then you need to ensure there’s a spatial index on your collection:

MyCollection.rawCollection().createIndex( { location : "2dsphere" } )

The above is for a single geojson field with the key location, you’ll have to look up how to do it for an array of points

Now you have GeoJSON points and a spatial index, you can use $near queries (Only on the server!):

MyCollection.find({
   location: {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ <longitude> , <latitude> ]
       },
       $maxDistance: <distance in meters>,
       $minDistance: <distance in meters>
     }
   }
});
2 Likes

Brilliant! Thanks so much. I can’t await to put my app online.

1 Like

Does this code work properly? For me it shows error.

Which part throws an error? Inserting docs with GeoJSON, adding an index, or querying?