面试题答案
一键面试预处理操作
- 建立2dsphere索引:为了能够高效地进行地理空间查询,需要在经纬度坐标字段上建立2dsphere索引。假设文档中经纬度坐标存储在一个名为
location
的数组字段中(第一个元素为经度,第二个元素为纬度),在MongoDB中可以通过以下命令创建索引:
db.cityCollection.createIndex({ location: "2dsphere" });
查询语句
var center = [116.3975, 39.9085];
var distance = 200 * 1000; // 200公里转换为米
db.cityCollection.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: center
},
$maxDistance: distance
}
}
}, {name: 1, _id: 0});
上述查询语句中,$near
操作符用于查找距离指定点一定范围内的文档。$geometry
指定中心点的坐标,$maxDistance
指定最大距离(单位为米)。投影部分{name: 1, _id: 0}
表示只返回城市名称字段,不返回_id
字段。