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)) .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.
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));