对于最新的稳定版本,请使用 Spring Data MongoDB 4.4.0spring-doc.cadn.net.cn

对文档进行计数

模板 API 提供了各种方法来计算与给定条件匹配的文档数量。 其中之一概述如下。spring-doc.cadn.net.cn

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

在 SpringData MongoDB 的 3.x 之前版本中,count作使用 MongoDB 的内部集合统计信息。 随着 MongoDB 事务的引入,这不再可能,因为统计数据无法正确反映需要基于聚合的计数方法的事务期间的潜在变化。 所以在版本 2.x 中MongoOperations.count()如果没有正在进行的事务,则使用 collection statistics,如果正在进行,则使用 aggregation variant。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(...)使用空筛选条件查询的作将被委托给estimatedCount,只要没有活动的事务并且模板未绑定到会话。 仍然可以通过以下方式获得确切的数字MongoTemplate#exactCount,但可能会加快速度。spring-doc.cadn.net.cn

MongoDB 原生countDocuments方法和$matchaggregation,不支持$near$nearSphere但需要$geoWithin以及$center$centerSphere不支持$minDistance(见 jira.mongodb.org/browse/SERVER-37043)。spring-doc.cadn.net.cn

因此,给定的Query将被重写为countReactive-/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 使用 Count 源查询$near.
2 现在使用 重写的查询$geoWithin$center.
3 使用 Count 源查询$near$minDistance$maxDistance.
4 重写的 query 现在是$nor $geowithinCritierias 解决 Unsupported 问题$minDistance.