Mongodb – mongo cluster collection count showing different every time

countmongodb

I had a replica set earlier which I have converted to cluster.

Current configuration is:

  • 3 shard

  • 4 router

  • 4 config server

When I am trying to get count of one of collection sometime it is showing null and some time some value , why this is happening?

Please help.

Best Answer

First, of course you are always connecting to your cluster thru mongoS, so query (count) goes to cluster and not directly to one individual shard.

Second, you are connected to right DB when you do count, I have seen situations where user has accidentally changed/connected to wrong DB and count (of course) return NULL, because that collection don't exists on that current DB.

You can always use

db.getSisterDB("yourDB").collection.count()

where ever you are...

Actually count() returns "cached" (metadata) count from collection, if you want to have absolute value, use

db.getSisterDB("yourDB").collection.find({_id:{ $gt: MinKey, $lt:MaxKey} }, {_id:1}).itcount()

what is "slow" operation because it really goes in the collection and count how many documents is there.