空间查询

测试环境:192.168.1.55 单机
测试目标:GPS系统有用户画矩形,选时间,去查询在该时间段内,经过该区域的有哪些车。
该测试暂不计入时间属性,检查空间判断是否准确。

一. 为集合创建索引

db.location.ensureIndex({loc:"2dsphere"})

{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}

二. 添加地理坐标点
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7692891, 32.06119564] }, "posSpeed" : NumberLong(50)})
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7785248, 32.06083978] }, "posSpeed" : NumberLong(50)})
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7929215, 32.05925674] }, "posSpeed" : NumberLong(50)})
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7790411, 32.05290934] }, "posSpeed" : NumberLong(50)})
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7909451, 32.0506315] }, "posSpeed" : NumberLong(50)})
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7708792, 32.05242908 ] }, "posSpeed" : NumberLong(50)})
db.location.insert({ "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7820485, 32.05615053] }, "posSpeed" : NumberLong(50)})

三. 设置用户画的多边形
左下角: 118.7742723,32.05465114
左上角: 118.7735413,32.06239942
右上角: 118.7838528,32.06230075
右下角: 118.7837246,32.05418786

四. 查询
db.location.find({loc:{ 
$geoWithin :{ 
$geometry:{
type:"Polygon",
coordinates:[[[118.7742723,32.05465114],
[118.7735413,32.06239942],
[118.7838528,32.06230075],
[118.7837246,32.05418786],
[118.7742723,32.05465114]]]
}
}
}
}
)

五.结果 { "_id" : ObjectId("56a0779aa88d08fdb6b30b24"), "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7785248, 32.06083978 ] }, "posSpeed" : NumberLong(50) } { "_id" : ObjectId("56a077bea88d08fdb6b30b29"), "hostid" : "3000033", "hostno" : "苏34", "loc" : { "type" : "Point", "coordinates" : [ 118.7820485, 32.05615053 ] }, "posSpeed" : NumberLong(50) }
经过其他手段检测确实只有这两个点在多边形内。

原文地址:https://www.cnblogs.com/myibm/p/5939355.html