Igor Artamonov
Igor Artamonov

Reputation: 35961

Geospatial Index for inner structure

I have a collections names locations with data structures like:

{ 
  "_id" : ObjectId("4e95263f1783ae8487be26d4"),
  "name" : "test 1", 
  "location" : { 
     "coordinate" : { 
        "latitude" : 40.731987, 
        "longitude" : -73.999701
     },
     "address": "xxxxxxx"
  }
}

and want to make geo queries against location.coordinate field.

When I'm trying to add index I get following results:

$> db.locations.ensureIndex( { "location.coordinate" : "2d" } )
$> **** SyntaxError: syntax error (shell):0

Is it possible to use geospatial index for such structure?

Upvotes: 2

Views: 775

Answers (1)

RameshVel
RameshVel

Reputation: 65887

Since mongodb is based on GeoJSON format, its better to have the longitude element first

"location" : { 
     "coordinate" : {        
        "longitude" : -73.999701,
        "latitude" : 40.731987 
     },

In the mongodb geospatial page, you can see that in multiple places

By default, the index assumes you are indexing longitude/latitude and is thus configured for a [-180..180) value range.

and

The code assumes that you are using decimal degrees in (longitude, latitude) order. This is the same order used for the GeoJSON spec. Using (latitude, longitude) will result in very incorrect results, but is often the ordering used elsewhere, so it is good to double-check. The names you assign to a location object (if using an object and not an array) are completely ignored, only the ordering is detected.

Upvotes: 4

Related Questions