Joe.webdev
Joe.webdev

Reputation: 3

mongodb geolocation indexing and quering

I have following mongo document structure.

{
"geo": {
  "0": {
    "deliveryArea": {
     "0": {
       "lat": 50.449234773334,
       "lng": 30.52300029031
    },
     "1": {
       "lat": 50.449234773334,
       "lng": 30.52542980606
    },
     "2": {
       "lat": 50.45154573136,
       "lng": 30.52542980606
    },
     "3": {
       "lat": 50.45154573136,
       "lng": 30.52300029031
    }
  },
   "title": "Kiev, ....",
   "coords": {
     "lat": "50.4501",
     "lngt": "30.523400000000038"
  },
   "wholeCityDelivery": "false"
}

Questions:

  1. How to ensure_index for every element in deliveryArea [lat,lng] for geolocationg?
  2. How to build query to find documents with the point N[lat,lng] in(belongs to) polygon deliveryArea.$

If you can do PHP - please)

Thanks!

Upvotes: 0

Views: 902

Answers (1)

Derick
Derick

Reputation: 36774

First of all, you need to change your data structure. MongoDB wants "longitude, lattitude" and it doesn't care which names you give to the fields—in general, I would use them without the field names. You also need to store your document without the "0" keys

So like:

{
    "geo": {
        "deliveryArea": [
             [ 30.52300029031, 50.449234773334 ],
        ]
    }
}

Then you need to set a 2D index on "geo.deliveryArea":

$collection->ensureIndex( array( "geo.deliveryArea" => "2d" ) );

Information on how to build queries can be at http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-BoundsQueries However, in your case you want to find a delivery area for a point, instead of checking whether stored points fit in a given area, and MongoDB can not do that directly as its 2d index can only store points. Please file a feature request at http://jira.mongodb.org

Upvotes: 3

Related Questions