Why the CountDocuments doesn't support $geoNear

Hello, when I set a filter has $geoNear, $near, and $nearSphere and use the filter in CountDocuments, I will get error (BadValue) $geoNear, $near, and $nearSphere are not allowed in this context. what’s the root reason that these operators not allowed.

Is it because the searching or counting using $geoNear, $near and $nearSphere are time consuming and will impact the performance?

thanks,

James

Hi James,

The filter parameter for CountDocuments becomes a $match aggregate stage. Because $geoNear is also an aggregation stage, it cannot be used inside of the $match one.

To do this, you can use Collection.Aggregate rather than Collection.CountDocuments. Your aggregation would have two stages: $geoNear and $count to output the number of documents found.

Hello Divjot,

Very clear. Thank you!

James