我正在进行地理位置查询,希望获得满足地理位置查询的集合总数。 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公里的10/6378.1,请参阅Calculate Distance using Spherical Geometry了解更多信息。

还值得一提的是,尽管$centerSphere在没有地理空间索引的情况下工作,但地理空间索引比未索引的等效索引支持更快的查询。

10-01 06:27