MST

星途 面试题库

面试题:MongoDB Shell高级数据类型操作与性能优化

在MongoDB Shell中,有一个集合存储大量的地理空间数据,文档结构为{ '_id': ObjectId('...'), 'location': { 'type': 'Point', 'coordinates': [longitude, latitude] } }。现在需要查询距离某个指定坐标点(例如[10, 20])半径100公里内的所有文档,并按照距离从近到远排序。请编写完整的MongoDB Shell查询语句,并阐述如何对这种地理空间查询进行性能优化。
17.1万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试

查询语句

db.collection.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [10, 20]
            },
            $maxDistance: 100000 // 100公里转换为米,1公里 = 1000米
        }
    }
}).sort({
    dist: 1
});

性能优化

  1. 建立索引:对location字段建立2dsphere索引,以加速地理空间查询。
    db.collection.createIndex({ location: "2dsphere" });
    
  2. 减少返回字段:只返回需要的字段,避免返回不必要的大文档,减少数据传输量。例如:
    db.collection.find({
        location: {
            $near: {
                $geometry: {
                    type: "Point",
                    coordinates: [10, 20]
                },
                $maxDistance: 100000
            }
        }
    }, { _id: 1, location: 1 }).sort({
        dist: 1
    });
    
  3. 批量处理:如果需要处理大量结果,可以采用批量获取数据的方式,减少单次查询的数据量。
  4. 限制结果集:如果只需要获取部分最近的文档,可以使用limit方法限制返回的文档数量。例如:
    db.collection.find({
        location: {
            $near: {
                $geometry: {
                    type: "Point",
                    coordinates: [10, 20]
                },
                $maxDistance: 100000
            }
        }
    }).sort({
        dist: 1
    }).limit(10);