此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 Spring Data MongoDB 5.0.4spring-doc.cadn.net.cn

统计文档数量

模板 API 提供了多种方法来统计匹配给定条件的文档数量。 下面列出了其中一种方法。spring-doc.cadn.net.cn

template.query(Person.class)
    .matching(query(where("firstname").is("luke")))
    .count();

在 Spring Data MongoDB 3.x 之前的版本中,count 操作使用的是 MongoDB 内部的集合统计信息。 随着MongoDB 事务的引入,这种方式不再可行,因为在事务过程中,统计信息无法正确反映可能发生的变更,因此需要采用基于聚合(aggregation)的计数方式。 因此,在 2.x 版本中,MongoOperations.count() 在没有进行中的事务时会使用集合统计信息,而在存在事务时则使用聚合变体。spring-doc.cadn.net.cn

从 Spring Data MongoDB 3.x 起,任何 count 操作都会通过 MongoDB 的 countDocuments 使用基于聚合的计数方法,无论是否存在过滤条件。 如果应用程序可以接受基于集合统计信息的限制,则 MongoOperations.estimatedCount() 提供了一种替代方案。spring-doc.cadn.net.cn

通过将 MongoTemplate#useEstimatedCount(…​) 设置为 true,当执行使用空过滤查询的 MongoTemplate#count(…​) 操作时,只要当前没有活跃的事务且模板未绑定到会话,该操作将被委托给 client-session-transactions.html。 仍然可以通过 MongoTemplate#exactCount 获取精确的计数值,但此举可能会提升性能。spring-doc.cadn.net.cn

MongoDB 原生的 countDocuments 方法和 $match 聚合操作不支持 $near$nearSphere,但需要配合 $geoWithin 以及 $center$centerSphere 使用,而这些组合不支持 $minDistance(参见 jira.mongodb.org/browse/SERVER-37043)。spring-doc.cadn.net.cn

因此,对于 Query 操作,将使用 count-/Reactive 对给定的 MongoTemplate 进行重写,以绕过如下所示的问题。spring-doc.cadn.net.cn

{ location : { $near : [-73.99171, 40.738868], $maxDistance : 1.1 } } (1)
{ location : { $geoWithin : { $center: [ [-73.99171, 40.738868], 1.1] } } } (2)

{ location : { $near : [-73.99171, 40.738868], $minDistance : 0.1, $maxDistance : 1.1 } } (3)
{$and :[ { $nor :[ { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 0.01] } } } ]}, { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 1.1] } } } ] } (4)
1 使用 $near 进行计数源查询。
2 重写后的查询现在使用 $geoWithin$center
3 使用 $near 并结合 $minDistance$maxDistance 进行计数源查询。
4 重写的查询现在结合了 $nor$geowithin 条件,以规避不支持的 $minDistance