MongoDB中查询指定距离内坐标数据的详细教程

silverwq
2022-06-21 / 0 评论 / 258 阅读 / 正在检测是否收录...

创建数据和索引

创建集合

db.testGps.insert(
{
"_id" : NumberLong("908531"),
"_class" : "com.xxxxx",
"loc" : {
    "type" : "Point",
    "coordinates" : [
        121.4624,
        31.2262
    ]
}
});

创建2dsphere索引

db.testGps.createIndex( 
   {"loc" : "2dsphere" }
);

距离查询

第一种方式

// 返回单位为 米
db.testGps.aggregate([
{
 $geoNear: {
    near: { type: "Point", coordinates: [121.462,31.226 ] },//coordinates: [0,0] 经度,维度
    distanceField: "dis.calculated",
    // maxDistance: 50000,             //指定最大距离,不指定则为最大值
    query: { "_id":NumberLong("908531") }, //查询条件
    // includeLocs: "dist.location",
    // num: 5,  //返回的行数 ,不写:默认返回所有
    spherical: true, //2dsphere 必须指定
    // distanceMultiplier:63781 // 不需要
 }
}])

第二种方式

//若需要距离单位为  米  则指定  // distanceMultiplier: 6378137 
//若需要距离单位为 千米 则指定  // distanceMultiplier: 6378 
db.runCommand({
 "geoNear":"testGps",
 "near":[121.462,31.226 ] ,
 // "num":10, 
 spherical:true,
 distanceMultiplier: 6378137,  
 maxDistance:10, 
  distance:"dis"   //距离别名
 })
0

评论 (0)

取消