MongoDB 中遇到的坑
Mongodb count
-
在项目中遇到一个这样的问题, 一个集合通过find查询的出来的结果是136, 而通过db.collection.find().count()之后的结果是79
-
本以为是工具的问题,但通过去mongo shell 直接去查询得到一样的结果
-
之后查阅了一番资料,终于在mongo的官方文档上找到了答案,得到答案很让我吃惊,竟然是建议我不要在不添加查询的条件的基础上进行count操作
-
原文如下:
-
Avoid using the db.collection.count() method without a query predicate since without the query predicate, the method returns results based on the collection’s metadata, which may result in an approximate count. In particular,
- On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
- After an unclean shutdown, the count may be incorrect.
-
For counts based on collection metadata, see also collStats pipeline stage with the count option.
-
通过这个可以看出,我这次遇到很可能是因为一次意外的关闭,导致了一些数据没有被记录上,从而导致count数据错误