【问题标题】:Mongo go driver's DocumentCount does not support $nearSphereMongo go驱动的DocumentCount不支持$nearSphere
【发布时间】:2019-09-10 16:15:40
【问题描述】:

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

我得到的错误是: (BadValue) 在此上下文中不允许使用 $geoNear、$near 和 $nearSphere

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)

【问题讨论】:

  • 查询是什么?
  • 该错误很有帮助,但您需要在问题中包含相关代码。
  • 我已经添加了示例代码。

标签: mongodb go mongo-go


【解决方案1】:

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

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

方法countDocuments()本质上包装了聚合管道$match$group。有关更多信息,请参阅The Mechanics of 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.1为10公里,请参阅Calculate Distance using Spherical Geometry了解更多信息。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2020-03-14
    • 2020-04-02
    • 2015-12-18
    • 2021-08-22
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多