mongodb - Mongo go 驱动的 DocumentCount 不支持 $nearSphere

标签 mongodb go mongo-go

我正在处理地理位置查询,我想获得满足地理位置查询的集合总数。 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)

最佳答案

(BadValue) $geoNear, $near, and $nearSphere are not allowed in this context

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

countDocuments() 方法本质上包装了聚合管道 $match$group。参见 The Mechanics of countDocuments()想要查询更多的信息。有许多查询运算符受到限制:Query Restrictions , 其中之一是 $nearSphere运算符(operator)。

另一种方法是使用 [$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 在没有地理空间索引的情况下工作,地理空间索引支持比未索引的等效项快得多的查询。

关于mongodb - Mongo go 驱动的 DocumentCount 不支持 $nearSphere,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874683/

相关文章:

mongodb - mongo-go-driver获取插入的文档

mongodb - 组合文字go中缺少类型,而map文字go中缺少键

mongodb - 在 mongodb-go-driver 中通过子字符串正则表达式查询查找条目

c# - 如何在mongodb中选择嵌套文档?

node.js - Mongoose:使用带有限制的 $in 运算符

javascript - 您能解释一下为什么不需要在 Promise 函数中放入值吗?

api - 不匹配的类型 *string 和 string

javascript - 在响应之前向文档添加其他字段

go - 在 Golang 中像 PHP 一样打印网页源代码的一部分

go - 如何在 Go 函数中正确传递参数?