1. LBS geospatial Index
LBS-related projects generally store coordinates of the longitude and latitude of each location. If you want to query nearby locations, you need to create an index to improve query efficiency. Mongodb has created a geospatial index for such queries. 2d and 2dsphere indexes.
2. Create an index
Create a places set to store the location. The loc field is used to store the GeoJSON Point of the region data.
db.places.insert( { loc : { type: "Point", coordinates: [ -73.97, 40.77 ] }, name: "Central Park", category : "Parks" })db.places.insert( { loc : { type: "Point", coordinates: [ -73.88, 40.78 ] }, name: "La Guardia Airport", category : "Airport" })
Create an index
db.places.ensureIndex( { loc : "2dsphere" } )
The parameter is not 1 or-1, and is 2 dsphere. You can also create a composite index.
db.places.ensureIndex( { loc : "2dsphere" , category : -1, name: 1 } )
3. Query
$ Geometry indicates the queried geometric image.
3.1 query the polygon range value
Type: polygon
db.places.find( { loc : { $geoWithin : { $geometry : { type : "Polygon" , coordinates : [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] } } } } )
3.2 query nearby values
Use $ near to query nearby locations.
db.places.find( { loc : { $near : { $geometry : { type : "Point" , coordinates : [ <longitude> , <latitude> ] } , $maxDistance : <distance in meters> } } } )
3.3 query the values in the circle
When querying a circle, you must specify the center and radius.
db.places.find( { loc : { $geoWithin : { $centerSphere : [ [ -88 , 30 ] , 10 ] } } } )
[-88, 30] is the longitude and latitude, and 10 is the radius.
Address: http://blog.csdn.net/yonggang7/article/details/28109463