此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Data MongoDB 4.5.2spring-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 之前版本中,计数作使用 MongoDB 的内部收集统计信息。 随着MongoDB事务的引入,这不再可能,因为统计数据无法正确反映需要基于聚合的计数方法的事务期间的潜在变化。 所以在 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(...)使用空筛选查询的作将委托给estimatedCount,只要没有活动事务并且模板未绑定到会话即可。 仍然可以通过以下方式获得准确的数字MongoTemplate#exactCount,但可能会加快速度。spring-doc.cadn.net.cn

MongoDBs 原生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.