代码之家  ›  专栏  ›  技术社区  ›  Ron

使用let变量的管道和geoIntersects查找

  •  5
  • Ron  · 技术社区  · 7 年前

    我正在努力寻找符合我条件的社区-the boundries let 在我的 pipeline $match

    邮政实体示例:

    {
      _id: ObjectId,
      ...,
      location: {
        ...,
        coordinates: {
          type: 'Point',
          coordinates: [number, number]
        }
      }
    };
    

    邻域实体示例:

    {
      _id: ObjectId,
      ...,
      boundries: {
        type: 'Polygon',
        coordinates: [ [ [number, number], [number, number], [number, number], [number, number], [number, number] ] ]
      }
    };
    

    我试图“修复”的查询示例:

    db.posts.aggregate([
      { $match: { _id: ObjectId('5a562e62100338001218dffa') } },
      {
        $lookup: {
          from: 'neighborhoods',
          let: { postCoordinates: '$location.coordinates.coordinates' },
          pipeline: [
            {
              $match: {
                boundries: {
                  $geoIntersects: {
                    $geometry: {
                      type: 'Point',
                      coordinates: '$$postCoordinates'
                    }
                  }
                }
              }
            }
          ],
          as: 'neighborhoods'
        }
      }
    ]);
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   s7vr    7 年前

    很遗憾,无法从文档字段填充坐标。

    地理空间是查询表达式和 $let 变量只允许在 $match 具有 $expr 中聚合表达式的变量 $lookup 管道。

    获取匹配记录的坐标的第一步。

    var result =  db.posts.findOne({ _id: ObjectId('5a562e62100338001218dffa')},{ _id: 0, 'location':1});
    

    第二步在多边形中寻找点。

    db.neighborhoods.find(
       {
         "boundries": {
           $geoIntersects: {
              $geometry: {
                 type: "Point" ,
                 coordinates: result.location.coordinates.coordinates
              }
           }
         }
       }
    )
    
    推荐文章