MST

星途 面试题库

面试题:MongoDB聚合框架匹配阶段与文本搜索及地理空间结合

假设MongoDB集合中存储了店铺信息,文档结构如下:{ 'name': '字符串', 'address': { 'city': '字符串', 'location': { 'type': 'Point', 'coordinates': [经度, 纬度] } }, 'description': '字符串','reviews': [ { 'rating': 数值 } ] }。要求编写一个聚合管道,使用匹配阶段筛选出位于特定城市(假设为'New York'),且店铺描述中包含特定关键词(假设为'organic'),并且平均评分大于4分,同时距离给定坐标点([ - 73.98, 40.75 ])在10公里范围内的店铺文档。你需要考虑到MongoDB文本索引及地理空间索引的应用。
42.9万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
  1. 创建索引
    • 文本索引
      db.shops.createIndex({description: "text"})
      
    • 地理空间索引
      db.shops.createIndex({"address.location": "2dsphere"})
      
  2. 编写聚合管道
    db.shops.aggregate([
        {
            $match: {
                "address.city": "New York",
                $text: {
                    $search: "organic"
                },
                "reviews.rating": {
                    $exists: true
                }
            }
        },
        {
            $unwind: "$reviews"
        },
        {
            $group: {
                _id: "$_id",
                name: { $first: "$name" },
                address: { $first: "$address" },
                description: { $first: "$description" },
                averageRating: { $avg: "$reviews.rating" }
            }
        },
        {
            $match: {
                averageRating: { $gt: 4 },
                "address.location": {
                    $near: {
                        $geometry: {
                            type: "Point",
                            coordinates: [-73.98, 40.75]
                        },
                        $maxDistance: 10000
                    }
                }
            }
        }
    ]);
    

解释:

  • 首先创建文本索引和地理空间索引,以提高查询效率。
  • 第一个$match阶段筛选出城市为New York且描述中包含organic的店铺,同时确保reviews.rating字段存在。
  • $unwind阶段将reviews数组展开,以便后续计算平均评分。
  • $group阶段重新组合文档,并计算平均评分。
  • 最后一个$match阶段筛选出平均评分大于4且距离给定坐标点在10公里范围内的店铺。