仅仅是tips,我们用的3.6版本,存在这种情况。4.0版本以后就没了。
背景
一般来说,除了由于secondary延迟可能造成查询secondary节点数据不准以外,关于count的准确性问题,在MongoDB4.0官方文档中有这么一段话
On a sharded cluster, db.collection.count() without a query predicate can result in an inaccurate count iforphaned documents exist or if a chunk migration is in progress.
To avoid these situations, on a sharded cluster, use the db.collection.aggregate() method
而MongoDB3.6官方文档却是这么描述的
On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.
To avoid these situations, on a sharded cluster, use the db.collection.aggregate() method
也就是说,MongoDB4.0分片集群模式下,针对不带谓词条件的全表count操作的返回结果是不准确的,主要包括以下两种场景。在MongoDB4.0以前的版本,即使不带谓词条件,在以下两种场景下count值也不准。
1 存在孤立文档
2 mongo分片集群内部正在进行move chunk操作
本文主要针对这两种场景,分析count不准的原因和规避措施