I have a collection in mongodb named users. I am trying to find count of all documents in the collection.
Surprisingly following queries are giving different results. For
db.users.find({}).count()
and
`db.users.count()`
the output is 533911, and for
db.users.aggregate(
[
{ $group: { _id: "$_id" } },
{ $group: { _id : null, count : { $sum : 1 } } }
]
)
and
db.users.aggregate(
[
{ $group: { _id : null, count : { $sum : 1 } } }
]
)
the output is 533950.
Can anyone tell me why aggregation and normal queries are returning different results ? Thanks in advance for any help.
I see 2 possible reasons :
If your collection is sharded, you should use the aggregation framework to count documents because the count operation may be inaccurate due to chunk moves or orphaned documents. How to count in Sharded Clusters
If you are using WiredTiger storage engine (which is most likely now as it's the default since V3.2), the statistics stored by WiredTiger can be inaccurate after an unclean shutdown. You should run a db.collection.validate() on each collections. WiredTiger unclean shutdown
Note : You can reduce the "confusion" by removing the orphaned documents with the cleanupOrphaned command but in a sharded environment you should always use the aggregation framework.
db.users.aggregate(
[
{ $group: { _id: "$_id" } },
{ $group: { _id : null, count : { $sum : 1 } } }
]
)
is counting null values also.
db.users.count()
not counting null values.