面试题答案
一键面试设计思路
- 地理空间索引设计:使用MongoDB的2dsphere索引来处理GeoJSON格式的地理位置数据。2dsphere索引专门用于处理球形地球表面的地理空间数据,适用于经纬度坐标,非常适合本题中的地理位置查询。
- 时间范围限制:为了获取最近一周的签到记录,需要在查询中对签到时间
check - in_time
进行筛选。
MongoDB命令
- 创建地理空间索引:
db.users.createIndex({ location: "2dsphere" });
此命令在users
集合的location
字段上创建2dsphere索引。
- 查询某一区域内最近一周的签到记录:
// 计算一周前的时间
var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
db.users.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
[
[x1, y1],
[x2, y2],
[x3, y3],
[x1, y1]
]
]
}
}
},
check - in_time: {
$gte: oneWeekAgo
}
});
在上述查询中:
$geoWithin
操作符用于查询位于指定多边形区域内的文档。将[x1, y1]
、[x2, y2]
、[x3, y3]
替换为实际的多边形顶点坐标。$gte
操作符用于筛选出签到时间在一周前(含)之后的记录。