MongoDB series five (geo-spatial Index and query).

Source: Internet
Author: User
Tags mongodb

First, the latitude and longitude of the representation way

The storage of latitude and longitude in MongoDB has its own set of specifications (mainly for the purpose of establishing a geospatial index on that field). There are two ways, namely Legacy coordinate Pairs (the word does not know how to translate ...). ) and GeoJSON.

    • Legacy coordinate Pairs

Legacy coordinate Pairs There are two ways to store latitude and longitude, you can use an array (preferred) or an embedded document.

Array:

<field>: [<longitude>, <latitude>]

Embedded documents:

<field >: {<field1>: <longitude> < field2>: <latitude> Span class= "P" >

< Span class= "o" > < Span class= "p" >tips: Valid longitude values are between 180 and 180. Valid latitude values are between 90 and 90.

    • < Span class= "NX" > < Span style= "color: #000000;" > GeoJSON

GeoJson is much more powerful than Legacy coordinate Pairs, Legacy coordinate Pairs is only used to preserve a latitude and longitude, and GeoJson can be used to specify points, lines, and polygons.

A point can be represented by an array of two elements, such as [longitude, Latitude] ([longitude, Latitude]):

{
"Geometry": {
"Type": "Point",
"Coordinates": [125.6, 10.1]
}
}

A line can be represented by an array of dots:

{
"Geometry": {
"Type": "LineString",
"Coordinates": [[125.6, 10.1],[125.6,10.2],[125.6,10.3]]
}
}

Polygons are represented as lines (all arrays of dots), but "type" is different:

{
"Geometry": {
"Type": "Polygon",
"Coordinates": [[125.6, 10.1],[125.5,10.2],[125.7,10.3]]
}
}

The type is in addition to point, LineString (line), Polygon (Polygon), MultiPoint (multipoint), multilinestring (multiple lines), and Multipolygon (multiple polygons).

The name of the "Geometry" field can be arbitrary, but the child object is specified by Geojson and cannot be changed.

ii. Geographical Spatial index
    • 2dsphere Index

The 2dsphere index is used for maps of the Earth's surface type, allowing the use of Legacy coordinate Pairs saved in the latitude and longitude fields and the point, line, and Polygon fields saved using the Geojson format.

  Db.world.ensureIndex ({"Geometry": "2dsphere"})
    • 2d Index

For aspheric maps (game maps, time-continuous data, and so on), you can use the "2d" index instead of "2dsphere".

2d indexes are only allowed on latitude and longitude fields saved in Legacy coordinate Pairs.

  Db.world.ensureIndex ({"Geometry": "2d"})
    • Difference:

The 2dsphere index supports only spherical queries (that is, queries on spherical geometry).

The 2d index supports planar queries (that is, queries on planar geometries) and some spherical queries. Although 2d indexes support some spherical queries, using a 2d index on these spherical queries can lead to errors, such as a large number of distorted distortions near the poles.
2d indexes can only be indexed to points. You can save an array of points, but it will only be saved as an array of points, not as a line. This is an important distinction, especially for "$geoWithin" queries. If you save a street as an array of points, the document matches the $geowithin if one of the points is within the given shape. However, lines made up of these points are not necessarily completely contained within this shape.

Iii. Geo-Spatial query

There are several different types of geospatial queries available: intersection (intersection), inclusive (within), and proximity (nearness).

    • $geoIntersects

Definition: Indicates the document that intersects the query location.

Supported indexes: 2dsphere

Geometric operators:

      1. $geometry (2dsphere index only, specify geometry in Geojson format)
    • $geoWithin

Definition: Indicates a document that is completely contained in a region.

Supported indexes: 2dsphere, 2d

Geometric operators:

    1. $box (2d index only, all documents within a rectangular range are queried)
    2. $center (2d index only, all documents within a circular range are queried)
    3. $polygon (2d index only, all documents within the polygon range are queried)
    4. $centerSphere (2d Index and 2dsphere index are supported, all documents within spherical circle range are queried)
    5. $geometry (2dsphere index only, specify geometry in Geojson format)
    • $near

Definition: Indicates the document with the query location from the nearest to farthest.

Supported indexes: 2dsphere, 2d

Geometric operators:

    1. $maxDistance (supports 2dsphere indexes and 2d indexes, specifying the maximum distance for query results)
    2. $minDistance (only 2dsphere indexes are supported, specifying the minimum distance for query results)
    3. $geometry (2dsphere index only, specify points in Geojson format)
    • $nearSphere

Definition: Use spherical geometry to calculate the distance from the near sphere, pointing to the document from the nearest to the farthest from the query location.

Supported indexes: 2dsphere, 2d

Geometric operators:

    1. $maxDistance (supports 2dsphere indexes and 2d indexes, specifying the maximum distance for query results)
    2. $minDistance (only 2dsphere indexes are supported, specifying the minimum distance for query results)
    3. $geometry (2dsphere index only, specify points in Geojson format)
Iv. Practice
    • The "$geoIntersects" operator to find the document that intersects the query location?
Db.driverPoint.find (   {     coordinate: {       $geoIntersects: {          $geometry:             {"Polygon" ,             coordinates: [               118.193828, 24.492242], [118.193953, 24.702114], [118.19387, 24.592242],[118.193828, 24 .492242]]}}}   )
View Code

Tips : coordinates represents a polygon, the first point and the last point must be the same, so that you can spell a pair of edges!

    • "$geoWithin" operator to find a document that is completely contained in an area?
Db.driverPoint.find (   {     coordinate: {       $geoWithin: {          $geometry:             {"Polygon" ,             Coordinates: [               118.193828, 24.492242], [118.193953, 24.702114], [119.19387, 28.792242],[118.193828, 24.4922 ]]}}}   )
View Code
    • The "$geoWithin" operator finds a document within a rectangular range?
Db.driverPoint.find ({  coordinate: {     $geoWithin: {        $box: [          118.0,24.0 ],          120.0,30.0 ]        ]   }})
View Code

Tips : "$box" accepts an array of two elements: the first element specifies the coordinates of the lower-left corner, and the second element specifies the coordinates of the upper-right corner.

    • "$geoWithin" operator to find the document in the Circle range?
Db.driverPoint.find ({  coordinate: {     $geoWithin: {         118.067678, 24.444373], ten ]      }  }})
View Code

Tips : "$center" accepts an array of two elements as a parameter: The first element is a point that specifies the center of the Circle, and the second parameter specifies the radius.

    • "$geoWithin" operator to find the document within the polygon range?
Db.driverPoint.find ({  coordinate: {     $geoWithin: {         118.067678, 24.444373], [119.067678, 25.444373], [120.067678, 26.444373]}}}  )
View Code

tips: The last point in the $polygon list is connected to the first point to make a polygon.

    • The "$geoWithin" operator finds a document within the spherical circle range?
Db.driverPoint.find ({  coordinate: {     $geoWithin: {         118.067678, 24.444373], 10/3963.2]      }  }})
View Code

Tips: This example represents all documents within 10 miles of the center point from [118.067678, 24.444373], and the query converts the distance to radians by dividing the Earth's approximate equatorial radius (3963.2 miles).

    • $near find the document within the corresponding distance from a point?

GeoJson format (only 2dsphere index supported):

Db.driverPoint.find ({   coordinate: {     $near: {          $geometry:{"Point" ,           118.067678, 24.444373 ]       },              0}}   )
View Code

Legacy coordinate Pairs format (only 2d index supported):

Db.driverPoint.find ({   coordinate: {     118.193828, 24.492242 ],     0.10     }})
View Code

tips: 1, $near when the GeoJson format is used to finish, the distance unit is meters (meter).

2, $near when expressed in Legacy coordinate Pairs format, the distance unit is radians (radian).

3. "$near" is the only geospatial operator that automatically sorts query results: The return result of "$near" is sorted by distance from near.

V. Conclusion

What do you say? Learning this knowledge always gives me a special feeling of confusion. A little summary of it! MongoDB's query for geospatial is based on its indexing of geospatial space (i.e., 2dsphere and 2d). So, we just have to figure out when it's time to build a 2dsphere index, when it's time to build a 2d index, and then find the operator that works for that index is clear! In short, the latitude and longitude saved in the GeoJSON format must establish a 2dsphere index. The latitude and longitude saved in the Legacy coordinate Pairs format is only considered for the 2d index when the map is represented, and in other cases the 2dsphere index is selected.

Resources:

1. The second edition of MongoDB authoritative guide

2, https://docs.mongodb.com/manual/reference/operator/query-geospatial/

MongoDB series five (geo-spatial Index and query).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.