I am working on geo location query where I want to get total number of collections that satisfy geo location query. Mongo go library provides Document Count method with doesn't support filter based on geo location.
The error I am getting is: (BadValue) $geoNear, $near, and $nearSphere are not allowed in this context
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
You're getting this message due to the restricted use of db.collection.countDocuments().
The method countDocuments()
essentially wraps aggregation pipeline $match
and $group
. See The Mechanics of countDocuments() for more information. There are a number of query operators that are restricted : Query Restrictions, one of them being $nearSphere operator.
An alternative is to use [$geoWithin] and $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},
},
},
},
},
}}
Note that the maxDistance
in spherical geometry has to be in a radius. You need to convert the distance, for example 10/6378.1
for 10 kilometres please see Calculate Distance using Spherical Geometry for more information.
Also worth mentioning that although $centerSphere works without having a geospatial index, geospatial indexes support much faster queries than the unindexed equivalents.