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

文章讲述了MongoDB在分片后使用db.collection.count()可能得到不准确的结果,原因包括孤立文档、块迁移等。官方推荐通过db.collection.aggregate()方法中的$group阶段进行精确计数,以确保结果准确性。
摘要由CSDN通过智能技术生成

教训: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 } } }
     ]
)

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Running Sun丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值