MongoDB:count结果不准确的原因与解决方法

教训:MongoDB在分片后的集合上进行db.collection.count()操作时,出现结果不准确的现象,需要采用聚合的方法获取集合的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:


官方文档解释了这种现象的原因以及解决方法:
不准确的原因:
a.操作的是分片的集合(前提);
b.shard分片正在做块迁移,导致有重复数据出现
c.存在孤立文档(因为不正常关机、块迁移失败等原因导致)


解决方法:
使用聚合aggregate的方式查询count数量,shell命令如下:
db.collection.aggregate(
     [
       { $group: { _id: null, count: { $sum: 1 } } }
     ]
)

你可能感兴趣的:(算法,mongodb,数据库)