MST

星途 面试题库

面试题:MongoDB 2d索引在平面空间查询中的应用

假设有一个集合存储了地图上店铺的位置信息,每个文档包含店铺名称、位置坐标(以数组形式表示,如[longitude, latitude])。请阐述如何创建2d索引来支持高效的平面空间查询,例如查询距离某个给定坐标点5公里内的所有店铺。同时写出对应的MongoDB查询语句。
35.6万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试

创建 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
        }
    }
});