MongoDB geospatial index on an array (multikey + g

2019-08-10 06:07发布

问题:

Here is a simplified version of my data:

> db.foo.insert({"name" : "jim",  "locations" : [[10,10],[3,6],[1,2]]})
> db.foo.insert({"name" : "john",  "locations" : [[1,5],[2,4]]})

I would like to be able to do things like

> db.foo.find( { locations : { $near : [5,5] } } )

Is there a way to create a geospatial index on an array? Doing:

> db.foo.ensureIndex({locations: "2d"}) 

gives the following error:

geo values have to be numbers: { 0: [ 1.0, 5.0 ], 1: [ 2.0, 4.0 ] }

Any advice or resources would be very much appreciated.

回答1:

Currently, MongoDB's Geospatial indexes only support 2 coordinate indexes; you can also have only one geospatial index per collection.

They must be either an array of two numeric values, or a document of two numeric values.

Array:

  [40.889248, -73.898583]

Document:

{ "lat" : 40.889248, "lon" : -73.898583 }


回答2:

I've had a similar problem, my solution was to store the location in a separate location object and use a multi key index. Doing that in this case, your documents could look something like this:

{"name" : "jim",  "locations" : [{"location": [10, 10]}, {"location": [3, 6]}, {"location": [1, 2]}]}

and the ensureIndex would look something like this

db.foo.ensureIndex({"locations.location": "2d"}) // could also use 2dsphere