Mongoose: Model.countDocuments() throwing error when using $near

Created on 22 Aug 2018  路  4Comments  路  Source: Automattic/mongoose

Do you want to request a feature or report a bug?
bug (unless this is intended behaviour and I can't find documentation)

What is the current behavior?
Throws error:
MongoError: $near is not allowed inside of a $match aggregation expression

If the current behavior is a bug, please provide the steps to reproduce.
Execute Model.countDocuments() with a filter that includes a $near expression.

What is the expected behavior?
That it does not throw an error (like Model.count())

Please mention your node.js, mongoose and MongoDB version.
mongo v3.4.13
node v8.11.1
mongoose v5.2.9

docs

Most helpful comment

@Fonger is correct, we still need to find a workaround for this. Until we do, please continue to use count(). Even though it is deprecated, count() will not be formally removed from the API for a while

All 4 comments

This is an underlying library issue, they use aggregation and $match in pipeline to count the documents.

@Fonger is correct, we still need to find a workaround for this. Until we do, please continue to use count(). Even though it is deprecated, count() will not be formally removed from the API for a while

@vkarpov15 @peteboere

I think I find a workaround.
Since what we want is counting, we can use $center or $centerSphere to replace the query.

$near will return the matching documents from nearest to the furthest.
If what we want is just counting, we don't need such sorting. Just ensure the results are in specified ranges.

So replace $near with $geoWithin + $centerSphere

For example, the following works in aggregation and it will also take advantage of geo index

const area = { center: [<longitude>, <latitude>], radius: <radius>, spherical: true }
Model.where('location').within().circle(area).countDocuments().then(...)

@vkarpov15 I find these migration guide description in mongodb docs which suggests the same method.

Note: When migrating from Collection#count to Collection#countDocuments
the following query operators must be replaced:

| Operator | Replacement |
| -------- | ----------- |
| $where | $expr |
| $near | $geoWithin with $center |
| $nearSphere | $geoWithin with $centerSphere |

Was this page helpful?
0 / 5 - 0 ratings