Why the MongoDB Count Property Returns All Records

why mongodb count property returns all records

Why the MongoDB Count Property Returns All Records

Mongo DB Count Property

One of the things that caught me off guard the first time I used the MongoDB C# Driver was the fact that the Count property would return a different result then what I was expecting. An example of this issue is say you have 100 items in your database and you do a query like so:

[code lang=”csharp”]
int userCount = db.GetCollection("UserProfile")
.FindAs(Query.EQ("FirstName", FirstName))
.SetLimit(1).Count();
[/code]

You would think that result would return 1 because of the SetLimit(1). However the actual result will be 100.

You may find this as confusing as I did the first time. The reason for confusion is what I outlined in a previous post, When does the MongoDB C# Driver Get Data?, about understanding the differences between LINQ and how the Mongo C# Driver works.

The Count property is a standalone function and is not meant to be chained as a result of a previous query even though it can be appended to the end of a result. The Count property requires that you give it a query of it’s own in order to obtain the count of that query. By default it will take an empty query which will yield a result of the count of all records in the collection.

So if you really want to know how many users have the same first name you would write your query as such

[code lang=”csharp”]
int userCount = db.GetCollection("UserProfile")
.Count(Query.EQ("FirstName", FirstName));
[/code]

Antonio Chagoury

Hi, I'm Antonio, Founder and CEO of Maxiom Technology (formerly Inspector IT).I'm a technology executive and entrepreneur who has achieved consistent success in driving growth, generating revenue, and enhancing value in domestic and international markets through technology product innovations.

No Comments

Sorry, the comment form is closed at this time.