Counting Documents
模板 API 提供多种方法来计算匹配给定条件的文档数目。其中一个概述如下。
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();
在 SpringData MongoDB 的 3.x 之前的版本中,计数操作使用 MongoDB 的内部集合统计数据。随着 MongoDB Transactions 的引入,这不再可行,因为统计数据不能正确反映在事务期间的潜在更改,因此需要基于聚合的计数方法。因此在 2.x 版本中,MongoOperations.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.
从 Spring Data MongoDB 3.x 开始,任何 count
操作都会使用基于聚合的计数方法通过 MongoDB 的 countDocuments
,而不管是否存在筛选条件。如果应用程序对使用集合统计信息有局限性,MongoOperations.estimatedCount()
提供了一个备选方案。
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 |
MongoDB 的本机 MongoDBs native 因此,给定的 Therefore a given
|