面试题答案
一键面试查询语句
db.collection.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [10, 20]
},
$maxDistance: 100000 // 100公里转换为米,1公里 = 1000米
}
}
}).sort({
dist: 1
});
性能优化
- 建立索引:对
location
字段建立2dsphere索引,以加速地理空间查询。db.collection.createIndex({ location: "2dsphere" });
- 减少返回字段:只返回需要的字段,避免返回不必要的大文档,减少数据传输量。例如:
db.collection.find({ location: { $near: { $geometry: { type: "Point", coordinates: [10, 20] }, $maxDistance: 100000 } } }, { _id: 1, location: 1 }).sort({ dist: 1 });
- 批量处理:如果需要处理大量结果,可以采用批量获取数据的方式,减少单次查询的数据量。
- 限制结果集:如果只需要获取部分最近的文档,可以使用
limit
方法限制返回的文档数量。例如:db.collection.find({ location: { $near: { $geometry: { type: "Point", coordinates: [10, 20] }, $maxDistance: 100000 } } }).sort({ dist: 1 }).limit(10);