【问题标题】:lookup with pipeline and geoIntersects that use let variable使用 let 变量的管道和 geoIntersect 查找
【发布时间】:2018-09-06 14:40:03
【问题描述】:

我正在尝试查找符合我的条件的社区 - boundries 多边形与帖子的坐标相交,但我无法做到 - 无法在我的 pipeline $match 中使用 let

帖子实体示例:

{
  _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'
    }
  }
]);

【问题讨论】:

  • 您能否详细说明您面临的具体错误。
  • 对于使用let,你可以看到https://stackoverflow.com/questions/48518215/mongodb-aggregation-lookup-with-conditions可能对你有帮助

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

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

地理空间是查询表达式,$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
          }
       }
     }
   }
)

【讨论】:

  • 您的回答没问题,但对于我想找到他们的社区的多个实体(在这种情况下为帖子)来说,这更复杂。我制作了一个多点数组,然后与引擎盖相交,它可以工作,但我很难将正确的引擎盖映射到帖子。我决定走一条不同的路。将社区的 id 保存在名为“hoods”的字段中的帖子实体上,然后在每个帖子中保存所有 hoods 的 id,这样我就可以轻松查询所有需要的 hoods 和地图。
猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 2020-11-16
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多