MongoDB Geospatial Queries

2016-06-21  本文已影响146人  Yves_lau
db.restaurants.findOne()
{
    "_id" : ObjectId("55cba2476c522cafdb053add"),
    "location" : {
        "coordinates" : [
            -73.856077,
            40.848447
        ],
        "type" : "Point"
    },
    "name" : "Morris Park Bake Shop"
}

 db.neighborhoods.findOne()
{
    "_id" : ObjectId("55cb9c666c522cafdb053a1b"),
    "geometry" : {
        "coordinates" : [
            [
                [
                    -73.94732672160579,
                    40.62916656720943
                ],
                [
                    -73.94732672160579,
                    40.62916656720943
                ]
            ]
        ],
        "type" : "Polygon"
    },
    "name" : "Midwood"
}

# geoNear需要空间索引, 提高geoIntersects, geoWithin 效率
# 创建2dsephere索引
db.restaurants.createIndex({location:"2dsphere"})
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}
db.neighborhoods.createIndex({geometry:"2dsphere"})
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

db.neighborhoods.findOne({ geometry: { $geoIntersects: { $geometry: 
 { type: "Point", coordinates: [ -73.93414657, 40.82302903 ] } } } })

var neighborhood = db.neighborhoods.findOne( { geometry: { $geoIntersects: { $geometry: 
 { type: "Point", coordinates: [ -73.93414657, 40.82302903 ] } } } } )
db.restaurants.find( { location: { $geoWithin: { $geometry: neighborhood.geometry } } } ).count()

search in a circular region

以当前坐标为圆心,5mile为半径,within的餐馆
db.restaurants.find({ location: { $geoWithin: {
  $centerSphere: [ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ] } } })

注意:$centerSphere
‘s second argument accepts the radius in radians, so you must divide it by the radius of the earth in miles. See Calculate Distance Using Spherical Geometry for more information on converting between distance units.

search in distance

You may also use $nearSphere
and specify a $maxDistance
term in meters. This will return all restaurants within five miles of the user in sorted order from nearest to farthest:

var METERS_PER_MILE = 1609.34
db.restaurants.find({ location: { $nearSphere:
 { $geometry: { type: "Point", 
                coordinates: [ -73.93414657, 40.82302903 ] },
   $maxDistance: 5 * METERS_PER_MILE } } })
上一篇 下一篇

猜你喜欢

热点阅读