logo

Premium Support
24/7/365

Premium support customers may submit help-desk tickets using the form below.
Alternatively, the help-desk system can be accessed directly at support.maxiomtech.com. support@maxiomtech.com
info@maxiomtech.com
+1 (703) 942-9420
 

Why the MongoDB Count Property Returns All Records

Why the MongoDB Count Property Returns All Records

mongodbOne 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))
		.SetLimit(1).Count();

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 InspectorIT. 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.