Harald Pollak
Harald Pollak

Reputation: 151

MongoDB C# find.count() less then find.ToList().Count()

I know there is a similar question with Javascript, but reindex, doesn't change anything.

The code:

                var col = db.GetCollection<BsonDocument>(collectionName);

                var entries = col.Find<BsonDocument>( new BsonDocument() );
                if(_logger.IsDebugEnabled)
                    _logger.Debug($"got collection: \'{collectionName}\' with {entries.Count()} Entries.");


                var list = entries.ToList();
                if(_logger.IsDebugEnabled)
                    _logger.Debug($"{collectionName}-List has {list.Count()} Entries");

brings the result:

2020-04-23 16:07:44,935 [1] DEBUG got collection: 'MyCollection' with 3884 Entries.
2020-04-23 16:07:45,184 [1] DEBUG MyCollection-List has 3890 Entries 

In the MongoDB-Commandline the command

> db.MyCollection.count();
3884

Has anyone an idea whats wrong, as written at the beginn i have allreade tried to reIndex the Collection but no change.

I'm using the c# driver from nuget with the version: 2.10.3 The version of the Server is MongoDB 4.0.4

Upvotes: 1

Views: 86

Answers (2)

Harald Pollak
Harald Pollak

Reputation: 151

Thank you! Allso on the commandline there are differences between count() and count_documents() so every thing is clear. once again: thank you

Upvotes: 0

D. SM
D. SM

Reputation: 14480

count is not guaranteed to be accurate, and is deprecated for this reason. See documentation.

Use count_documents (added in recent drivers) to obtain an accurate count.

Upvotes: 1

Related Questions