This chapter introduces MongoDB's geospatial query, which supports geometric intersection and containment queries.
Application scenarios:
- Draw a circle on the map and query the data within the circle.
Prerequisite Tutorial
Geospatial Data Storage Formats for MongoDB
The prerequisites for querying data based on distance are as follows:
- Each document data contains a field for storing coordinate data, for example: the location field stores the coordinates of a store.
- Create a 2dsphere or 2d spatial index.
$geoWithin Operator
It is commonly used to query coordinate points contained within a specified geometric range, for example: when searching for houses by drawing on a map, draw an area on the map and query the houses within that area.
Syntax format:
{
<location field>: { // Query field
$geoWithin: {
$geometry: {
type: , // Only supports Polygon or MultiPolygon.
coordinates: [ <coordinates> ] // Collection of geometric coordinate points
}
}
}
}
Example:
db.places.find(
{
loc: { // The loc field stores the coordinate data
$geoWithin: {
$geometry: {
type: "Polygon" ,
coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] ] // Find data within this geometric area
}
}
}
}
)
Query for document data within the specified geometric area in the places collection.
$geoIntersects Operator
The difference from $geoWithin is that $geoIntersects is used to determine whether there is an intersection between two geometries.
Format:
{
<location field>: { // Field storing geometric coordinate points
$geoIntersects: {
$geometry: {
type: "<geojson object type>" , // Geometric type
coordinates: [ <coordinates> ] // Collection of geometric coordinate points, query data with intersection with this geometry
}
}
}
}
Example:
db.places.find(
{
loc: { // The loc field stores area data, which is a geometric shape
$geoIntersects: {
$geometry: {
type: "Polygon" ,
coordinates: [
[ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] // Query data with intersection with this geometry
]
}
}
}
}
)