面试题答案
一键面试创建 2d 索引
在 MongoDB 中,可以使用 createIndex
方法来创建 2d 索引。假设集合名为 shops
,位置坐标字段名为 location
,以下是创建 2d 索引的代码:
db.shops.createIndex({ location: "2d" });
MongoDB 查询语句
要查询距离某个给定坐标点 5 公里内的所有店铺,假设给定坐标点为 [longitude, latitude]
,以下是查询语句:
var point = [longitude, latitude];
var distance = 5000; // 5公里转换为米
db.shops.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: point
},
$maxDistance: distance
}
}
});