mongodbmongo-c-driver

$geoNear, $near, and $nearSphere are not allowed in this context error with Mongo C driver


I'm using the mongoc_collection_count_documents() function (driver version 1.23.1, MongoDB server version 5.0.13), this way:

long long n = mongoc_collection_count_documents(collection, q, NULL, NULL, NULL, &error);

where q is a bson_t variable that depends on the particular query.

With simple queries like {"score": 20} it works fine. However, if I try something something like this:

{
    "location" : {
        "$near" : {
            "$geometry" : {
                "type" : "Point",
                "coordinates" : [
                    2,
                    1
                ]
            },
            "$maxDistance" : 10
        }
    }
}

(I have a 2dsphere index for location field)

I get the following error:

$geoNear, $near, and $nearSphere are not allowed in this context

On the contrary, if I run the same query with db.c.count() at the Mongo Shell I don't get any error.

So I have two questions:


Solution

  • Thanks to the link provided by @Joe I have find the suggestion to use $geoWithin with $center instead of $near.

    The problem is that $geoWithin doesn't have a equivalence for $near's $minDistance. However, looking to this ticket at MongoDB JIRA the query can be formulated this way (e.g. being 10 max distance and 5 min distance):

    {
      $and: [
        { location: { $geoWithin: { $centerSphere: [ [ 2, 1 ], 10 ] } } },
        { location: { $not: { $geoWithin: { $centerSphere: [ [ 2, 1 ], 5 ] } } } }
      ]
    }
    

    More complicated, but it suffices my case (although I wonder why the "compact way" is now considered deprecated in count functions...)