You are browsing a version that is no longer maintained. |
Geospatial Queries
You can execute some special queries when using geospatial indexes like checking for documents within a rectangle or circle.
Mapping
First, setup some documents like the following:
1 <?php
/**
* @Document
* @Index(keys={"coordinates"="2d"})
*/
class City
{
/** @Id */
public $id;
/** @String */
public $name;
/** @EmbedOne(targetDocument="Coordinates") */
public $coordinates;
/** @Distance */
public $distance;
}
/** @EmbeddedDocument */
class Coordinates
{
/** @Float */
public $x;
/** @Float */
public $y;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Near Query
Now you can execute queries against these documents like the
following. Check for the 10 nearest cities to a given longitude
and latitude with the near($longitude, $latitude)
method:
GeoNear Command
You can also execute the geoNear command using the query builder's
geoNear()
method. Additional builder methods can be used to set options for
this command (e.g. distanceMultipler()
, maxDistance()
, spherical()
).
Unlike near()
, which uses a query operator, geoNear()
does not require
the location field to be specified in the builder, as MongoDB will use the
single geospatial index for the collection. Documents will be returned in order
of nearest to farthest.
If the model has a property mapped with @Distance, that field will be set with the calculated distance between the document and the query coordinates.
Within Box
You can also query for cities within a given rectangle using the
withinBox($x1, $y1, $x2, $y2)
method: