一数据结构
use lbs; db.lbs.insert( { loc:{ type: "Point", coordinates: [113.332264, 23.156206] }, name: "aaaaaa" } ) db.lbs.insert( { loc:{ type: "Point", coordinates: [113.330611, 23.147234] }, name: "bbbbb" } ) db.lbs.insert( { loc:{ type: "Point", coordinates: [113.328095, 23.165376] }, name: "cccccc" } )
二创建索引
db.lbs.ensureIndex( { loc: "2dsphere" } )
三检索
db.lbs.find( { loc: { $near:{ $geometry:{ type: "Point", coordinates: [113.323568, 23.146436] }, $maxDistance: 1000 } } } )
四平均距离最大距离
db.runCommand({geoNear:"lbs",near:[113.328568, 23.166436],num:10,spherical:true,distanceMultiplier:6378137,maxDistance:5000/6378137})//返回的dis字段为距离
db.lbs.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [113.328568, 23.166436] }, distanceField: "dist", //距离字段单位米 maxDistance: 5000, spherical: true } }, {$skip:0}, {$limit:10}, {$sort:{"dist":1}} // 1:asc -1:desc ])
上面两种方法返回的距离单位为米。最后一种方法支持分页,支持正反序排列。
访客评论