首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongo司机的DocumentCount不支持$nearSphere

Mongo司机的DocumentCount不支持$nearSphere
EN

Stack Overflow用户
提问于 2019-09-10 16:15:40
回答 1查看 402关注 0票数 1

我正在处理geo位置查询,其中我希望获得满足geo位置查询的集合总数。Mongo库提供了不支持基于地理位置的过滤器的文档计数方法。

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

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-12 00:07:06

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

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

countDocuments()方法本质上封装了聚合管道、$match$group。有关详细信息,请参阅countDocuments()的力学。有许多查询运算符受到限制:查询限制,其中一个是$nearSphere操作符。

另一种选择是使用$geoWithin和$centerSphere

代码语言:javascript
复制
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在没有地理空间索引的情况下工作,但地理空间索引支持的查询要比未索引的等价物快得多。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57874683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档