Question

All of the examples and implementations of geo search in Mongo, that I've been able to find, use an array property [lng, lat] to perform the search on:

An example record would be:

{
   name: 'foo bar',
   locations: [
     {
       name: 'franks house',
       geo: [-0.12, 34.51]
     },
     {
       name: 'jennifers house',
       geo: [-0.09, 32.17]
     }
   ]
}

And the resulting query:

db.events.find({ 'locations.geo': { $nearSphere: [ -0.12, 34.51 ], $maxDistance: 0.02 }})

This works fine, but the format of the record is not great for users to read or write because it's not self-documenting where lat and lng go in that array. There's room for gotchas. I'd like to make the records more human friendly:

{
   name: 'foo bar',
   locations: [
     {
       name: 'franks house',
       lat: 34.51,
       lng: -0.12
     },
     {
       name: 'jennifers house',
       lat: 32.17,
       lng: -0.09
     }
   ]
}

What would the resulting mongo query look like for this type of record? I haven't been able to find any examples of this so am wondering if it's even possible.

Was it helpful?

Solution

It's not recommended to use separate fields for latitude and longitude. The 2dsphere index is used to index geospatial data which requires an array of coordinates, see documentation. This is the reason you can't find examples for separate coordinate fields.

You should separate representation from data storage. Just because coordinates are stored in an array, you don't necessarily need to present them as an array to the user. For example you could use a pre call on save to store separate parameters in an array, something like:

var schema = new Schema(..);
schema.pre('save', function (next) {
  this.coordinates = [this.longitude, this.latitude]
  next();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top