MongoDB空间定位(点)与距离检索

MongoDB空间定位(点)与距离检索

测试数据:
db.mapinfo.insert({"address": "南京 禄口国际机场", "tags": ['A'], "location": {"type": "Point", "coordinates": [118.783799, 31.979234]}})
db.mapinfo.insert({"address": "南京 浦口公园", "tags": ['B'], "location": {"type": "Point", "coordinates": [118.639523, 32.070078]}})
db.mapinfo.insert({"address": "南京 火车站", "tags": ['C'], "location": {"type": "Point", "coordinates": [118.803032, 32.09248]}})
db.mapinfo.insert({"address": "南京 新街口", "tags": ['D'], "location": {"type": "Point", "coordinates": [118.790611, 32.047616]}})
db.mapinfo.insert({"address": "南京 张府园", "tags": ['A', 'B'], "location": {"type": "Point", "coordinates": [118.790427, 32.03722]}})
db.mapinfo.insert({"address": "南京 三山街", "tags": ['B', 'C'], "location": {"type": "Point", "coordinates": [118.788135, 32.029064]}})
db.mapinfo.insert({"address": "南京 中华门", "tags": ['C', 'D'], "location": {"type": "Point", "coordinates": [118.781161, 32.013023]}})
db.mapinfo.insert({"address": "南京 安德门", "tags": ['A', 'B', 'C', 'D'], "location": {"type": "Point", "coordinates": [118.768964, 31.99646]}})

一定要加索引
db.mapinfo.ensureIndex({location : "2dsphere"})
/**
mongodb 提供的地图索引有两种,分别是 2d 和 2dsphere。
2d 索引通过二维平面记录点坐标,支持在平面几何中计算距离,而 2dsphere 则支持在球面上进行距离的计算,并且支持 mongodb 的所有地理空间查询方法。
简单的理解,2dsphere 是 2d 的增强版。根据官方推荐,如果你的mongodb版本大于2.6
*/

检索规定半径以内数据(单位为米)
{location: {$near: {$geometry: {type: "Point", coordinates: [118.783799, 31.979234]}, $maxDistance: 5000}}} // 5000米以内数据
{location: {$nearSphere: {$geometry: {type: "Point", coordinates: [118.783799, 31.979234]}, $maxDistance: 5000}}} // 5000米以内数据

完整的查询语句
db.mapinfo.find({location: {$nearSphere: {$geometry: {type: "Point", coordinates: [118.783799, 31.979234]}, $maxDistance: 15000}}})


/**
按照离我最近排序,除了使用 $nearSphere 查询外,我们还可以使用 aggregate 来实现。
使用 aggregate 有两个好处。1.我们在进行排序的后,可以返回两点之间的距离。2.我们可以进行更为复杂的排序,例如我们可以先根据某个字段进行排序,然后该字段相同的情况下再根据距离排序。
使用 aggregate 查询时,我们还可以返回两点之间的距离,其中 distanceField 可以对距离字段进行重命名。
*/
db.mapinfo.aggregate([
   {
     $geoNear: {
        near: {type: "Point", coordinates: [118.783799, 31.979234]},
        distanceField: "distance",
        spherical: true,
        num: 5,
        maxDistance: 15000,
				query: {
			    address: {$regex:'安'}
				}
     }
   },
   { $skip: 0 },
   { $limit: 2 }
])

/**
如果我们希望查询以某个点为中心的圆几公里以内的数据,那你的姿势可以如下:
地球表面1弧度距离约为6378137米, 0.001弧度距离为6378米
*/
db.mapinfo.find({
    "location": {
        "$geoWithin": {
            "$centerSphere": [
                [
                    118.783799, 31.979234
                ],
                0.025 // 单位为弧度
            ]
        }
    }
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值