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

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

via:https://www.jianshu.com/p/c0a351927e69

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值