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:

int userCount = db.GetCollection("UserProfile")
		.FindAs(Query.EQ("FirstName", FirstName))

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

int userCount = db.GetCollection("UserProfile")
		.Count(Query.EQ("FirstName", FirstName));
Jonathan Sheely

Sr Software Engineer at Maxiom Technology. Jonathan is an out of the box thinker who has over 10 years experience building and supporting web application software and infrastructure. Jon specializes in ASP.NET C#, Javascript and CSS but is willing to learn anything that gets the job done.

No Comments

Sorry, the comment form is closed at this time.