1

我正在研究地理位置查询,我想获得满足地理位置查询的集合总数。Mongo go 库提供 Document Count 方法,不支持基于地理位置的过滤器。

我得到的错误是: (BadValue) $geoNear, $near, and $nearSphere are not allowed in this context

filter := bson.D{
    {
        Key: "address.location",
        Value: bson.D{
            {
                Key: "$nearSphere",
                Value: bson.D{
                    {
                        Key: "$geometry",
                        Value: bson.D{
                            {
                                Key:   "type",
                                Value: "Point",
                            },
                            {
                                Key:   "coordinates",
                                Value: bson.A{query.Longitude, query.Latitude},
                            },
                        },
                    },
                    {
                        Key:   "$maxDistance",
                        Value: maxDistance,
                    },
                },
            },
        },
    },
}
collection := db.Database("catalog").Collection("restaurant")
totalCount, findError := collection.CountDocuments(ctx, filter)
4

1 回答 1

0

(BadValue) 在此上下文中不允许使用 $geoNear、$near 和 $nearSphere

由于db.collection.countDocuments()的使用受限,您会收到此消息。

该方法countDocuments()本质上包装了聚合管道$match$group. 有关详细信息,请参阅countDocuments()的机制。有许多查询运算符受到限制:Query Restrictions,其中之一是$nearSphere运算符。

另一种方法是使用 [$geoWithin] 和$centerSphere

filter := bson.D{ 
  { Key: "address.location", 
    Value: bson.D{ 
        { Key: "$geoWithin", 
            Value: bson.D{ 
                { Key: "$centerSphere", 
                  Value: bson.A{ 
                            bson.A{ query.Longitude, query.Latitude } , 
                            maxDistance}, 
                }, 
            },
        },
    },
  }}

请注意,maxDistance球面几何必须在半径内。您需要转换距离,例如10/6378.110 公里,请参阅使用球面几何计算距离以获取更多信息。

还值得一提的是,虽然$centerSphere没有地理空间索引的情况下工作,但地理空间索引支持比未索引的等价物更快的查询。

于 2019-09-12T00:07:06.360 回答