MongoDB geospatial index on an array (multikey + g

2019-08-10 05:59发布

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.

2条回答
成全新的幸福
2楼-- · 2019-08-10 06:11

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 
查看更多
该账号已被封号
3楼-- · 2019-08-10 06:16

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 }
查看更多
登录 后发表回答