This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Data MongoDB 4.3.4! |
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Data MongoDB 4.3.4! |
The template API offers various methods to count the number of documents matching a given criteria. One of them outlined below.
template.query(Person.class)
.matching(query(where("firstname").is("luke")))
.count();
In pre-3.x versions of SpringData MongoDB the count operation used MongoDBs internal collection statistics.
With the introduction of MongoDB Transactions this was no longer possible because statistics would not correctly reflect potential changes during a transaction requiring an aggregation-based count approach.
So in version 2.x MongoOperations.count()
would use the collection statistics if no transaction was in progress, and the aggregation variant if so.
As of Spring Data MongoDB 3.x any count
operation uses regardless the existence of filter criteria the aggregation-based count approach via MongoDBs countDocuments
.
If the application is fine with the limitations of working upon collection statistics MongoOperations.estimatedCount()
offers an alternative.
By setting |
By setting |
MongoDBs native Therefore a given
|
MongoDBs native Therefore a given
|
1 | Count source query using $near . |
2 | Rewritten query now using $geoWithin with $center . |
3 | Count source query using $near with $minDistance and $maxDistance . |
4 | Rewritten query now a combination of $nor $geowithin critierias to work around unsupported $minDistance . |