教训:MongoDB 在分片后的集合上进行 db.collection.count() 操作时,出现结果不准确的现象,需要采用聚合的方法获取集合的 count 结果
插入数据后,使用 Studio 3T 查看数据量时,发现显示的 count 结果与插入的数据不一致,偶然会多出几条或十几条
通过谷歌发现,官方文档——( https://docs.mongodb.com/manual/reference/method/db.collection.count/ )中有解释这种现象:
-
On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documentsexist or if a chunk migration is in progress.
-
To avoid these situations, on a sharded cluster, use the $group stage of the db.collection.aggregate() method to $sum the documents. For example, the following operation counts the documents in a collection:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
官方文档解释了这种现象的原因以及解决方法:
不准确的原因:
- 操作的是分片的集合;
- shard 分片正在做块迁移,导致有重复数据出现
- 存在孤立文档(因为不正常关机、块迁移失败等原因导致)
解决方法:
使用聚合 aggregate 的方式查询 count 数量,命令如下:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)