Junyu Wu
Junyu Wu

Reputation: 379

mongodb geoNear for arrays of locations

I have a document like this:

{positions: [ [0.1, 0.1], [0.2, 0.2] ]}

I want to query the documents near a point [0.11, 0.11]. Something like this:

{positions: {$near: [0.11, 0.11]} }

How to add the 2d index and how to query? Thanks.

Upvotes: 1

Views: 2552

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

While your example data isn't the best the index creation and query are quite straightforward. To create the 2d index you only need the following command:

db.collection.ensureIndex( { positions: "2d" } )

Your data format of arrays within an array is quite valid. Queries are simple as well as you basically have the syntax:

db.collection.find({ positions: {$near: [-75, 111]} })

The only thing to be aware of is that without doing any projection you are getting the whole document back including the whole array of positions, and that this result will be repeated for any of the matching positions in the array.

Being new to this, you best put in some reading on MongoDB geospacial capabilities and make some decisions about which solution is going to be the best fit for your case. The following links make a good starting point:

http://docs.mongodb.org/manual/core/geospatial-indexes/#store-location-data

http://docs.mongodb.org/manual/administration/indexes-geo/

Upvotes: 3

Related Questions