mongodb - 使用 let 变量的管道和 geoIntersect 查找

标签 mongodb mongodb-query aggregation-framework

我正在尝试查找符合我的条件的社区 - boundries 多边形与帖子的坐标相交,但我无法做到 - 无法使用 let in我的 管道 $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'
    }
  }
]);

最佳答案

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

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

关于mongodb - 使用 let 变量的管道和 geoIntersect 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52206619/

相关文章:

mongodb - mongoimport 导入csv文件乱序

MongoDB 按字符串长度查找

mongodb - 如何使用 MongoDB 过滤子文档中的数组

MongoDB 按字段查找对象数组(连接条件和不相关的子查询)

ruby - mongodb 对计算值聚合框架进行排序/查询?

javascript - 如何将 JavaScript 中的 new Date() 格式化为 JSON 中的 ISODate

javascript - 蒙戈错误: topology was destroyed(when finding the documents) and instance pool was destroyed (when inserting documents)

java - 部分更新文档中的字段 - findAndModify 删除所有其他字段?

mongodb - 如何在mongodb中删除具有特定条件的重复项?

node.js - 子文件与 Mongoose 人口