You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合管道中geoNear未按距离过滤问题排查

MongoDB聚合管道未正确过滤距离超过100km的文档问题排查

问题根源

$geoNear阶段返回的distance字段单位是米,不是你以为的千米。你当前在$redact里写的['$lte' => ['$distance', 100]],实际是只保留距离≤100米的文档,而示例里的1460米(约1.46公里)远大于100米,自然不会被过滤掉。

修复方案

方案1:在$geoNear中直接设置maxDistance(推荐,性能更优)

把距离过滤逻辑提前到地理查询阶段,MongoDB会利用地理索引直接筛选符合条件的文档,避免后续多余的计算:

$pipeline = [            
    [
        '$geoNear' => [
            'near' => [
                'type' => 'Point',
                'coordinates' => $coordinates
            ],
            'spherical' => true,
            'distanceField' => 'distance',
            'maxDistance' => 100000 // 100千米 = 100000米
        ]    
    ],                        
    ['$sort' => ['distance' => 1]]      
]; 

方案2:修正$redact中的距离阈值

如果必须使用$redact阶段,把阈值改成100000米(对应100千米)即可:

$pipeline = [            
    [
        '$geoNear' => [
            'near' => [
                'type' => 'Point',
                'coordinates' => $coordinates
            ],
            'spherical' => true,
            'distanceField' => 'distance'
        ]    
    ],                        
    [
        '$redact' => [
            '$cond' => [
                'if' => [
                    // 100km = 100000米
                    ['$lte' => ['$distance', 100000]]
                ],
                'then' => '$$KEEP',
                'else'=> '$$PRUNE'
            ]
        ]
    ],
    ['$sort' => ['distance' => 1]]      
]; 

内容的提问来源于stack exchange,提问作者Eric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 12:17:18