Gena
Gena

Reputation: 187

Count incorrect in MongoDB

Tech:

mongodb://USER:[email protected]:1234,MYMONGO2.com:1234/DB_NAME?replicaSet=REPLICA_SET_NAME

Assumptions

Once a day I log a specific count on this collection (same parameters every time):

db.Products({"Package": "Box"}).count()
// actual code running in C#:
productsCollection.Find(p => p.Package == "Box").Count()

I expect the result to be the same or greater every day. But sometimes I get a smaller value. The next day it becomes correct again. It reproduced on two different environments.

Example:

I was trying to manually reproduce it both via C# and directly against Mongo, but failed (the value was always correct).

What's going on?

Upvotes: 11

Views: 497

Answers (1)

Boris
Boris

Reputation: 162

This is probably due to balancing round was taking place when you code was executed. From MongoDB documentation:

On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.

More about it here: MongoDB documentation

To get the exact result one should use the aggregation framework queries

Upvotes: 2

Related Questions