MongoDB geospatial index on an array (multikey + geospatial)

痞子三分冷 提交于 2019-12-24 07:07:21

问题


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 


来源:https://stackoverflow.com/questions/5570317/mongodb-geospatial-index-on-an-array-multikey-geospatial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!