首页 > 解决方案 > MongoDB Geospatial,项目匹配多点

问题描述

通过带有 Aggregate 的 MongoDB $geoNear 命令,我无法生成查询的 maxDistance 字段内的位置。

        array(
            '$geoNear'          => array(
                'near'             => array(
                    'type'            => "MultiPoint",
                    'coordinates'     => [ 
                        $city["geo"]["coordinates"][0], 
                        $city["geo"]["coordinates"][1] 
                    ],
                ),
                "distanceField"    => "distance",
                "maxDistance"      => 1*1609.34,
                "includeLocs"      => "locations",
                "spherical"        => true,
                "query" => array(
                    "status" => true
                ),
                "limit" => 500
            ),
        ),

使用 includeLocs 的文档声明“指定了标识用于计算距离的位置的输出字段。当位置字段包含多个位置时,此选项很有用。”,但是 includeLocs 字段包括所有多点位置。

mongodb 是否能够仅投影匹配的多点而不是存储的整个集合?

标签: phpmongodbgeospatialmongodb-geospatial

解决方案


我能够解决这个问题:

  1. 在 $geoNear 管道之后,添加一个 $unwind 阶段以展开“includeLocs”数组,即 {$unwind: '$locations.coordinates'}(确保展开坐标)。
  2. 使用 $geoWithin 地理空间运算符为“$match”添加另一个阶段,该字段专门标记为展开坐标字段,即“$locations.coordinates”。
  3. 最后添加一个 '$group' 阶段以将所有内容加入 _id 字段。

推荐阅读