2
votes

I have a documents contains list of location "boxes" (square area). Each box is represented by 2 points (bottom-left or south-west, top-right or north-east).

Document, for example:

{
   locations: [
        [[bottom,left],[top,right]],
        [[bottom,left],[top,right]],
        [[bottom,left],[top,right]]
   ]
}

I'm using 2d index for those boundaries points.

My input is a specific location point [x,y] and I want to fetch all documents that have at list one box that this point is located in it.

Is there any geospatial operator I can use to do that? How do I write this query?

1

1 Answers

2
votes

You can use the box operator, see: http://docs.mongodb.org/manual/reference/operator/query/box/#op._S_box with the following example taken directly from that page:

db.places.find( { loc : { $geoWithin : { $box :
                                      [ [ 0 , 0 ] ,
                                        [ 100 , 100 ] ] } } } )

It is worth noting that the 2d index is considered legacy. If you can convert to using GeoJSON and a 2dsphere index, then you can use the $geoWithin operator: see

http://docs.mongodb.org/manual/reference/operator/query/geoWithin/#op._S_geoWithin

GeoJSON has a number of other benefits, not least of which, is that it is easily transmitted and digested by web mapping apps such as OpenLayers or Leaflet.