我正在处理geo位置查询,其中我希望获得满足geo位置查询的集合总数。Mongo库提供了不支持基于地理位置的过滤器的文档计数方法。
我得到的错误是:(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)发布于 2019-09-12 00:07:06
(BadValue)在此上下文中不允许使用$geoNear、$near和$nearSphere
由于db.collection.countDocuments()的使用受到限制,您将收到这条消息。
countDocuments()方法本质上封装了聚合管道、$match和$group。有关详细信息,请参阅countDocuments()的力学。有许多查询运算符受到限制:查询限制,其中一个是$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公里请参阅用球面几何计算距离获得更多信息。
还值得一提的是,虽然$centerSphere在没有地理空间索引的情况下工作,但地理空间索引支持的查询要比未索引的等价物快得多。
https://stackoverflow.com/questions/57874683
复制相似问题