Geo location search


#1

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!


#2

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


#3

well by distance would be great


#4

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>
     }
   }
});

#5

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


#6

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


#7

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