登录
首页 >  Golang >  Go问答

Mongo go驱动的DocumentCount不支持$nearSphere

来源:stackoverflow

时间:2024-04-09 16:12:33 361浏览 收藏

你在学习Golang相关的知识吗?本文《Mongo go驱动的DocumentCount不支持$nearSphere》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我正在处理地理位置查询,我想获取满足地理位置查询的集合总数。 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 和 $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 在没有地理空间索引的情况下也可以工作,但地理空间索引支持的查询速度比未索引的同等索引快得多。

本篇关于《Mongo go驱动的DocumentCount不支持$nearSphere》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>