Bob Tway
Bob Tway

Reputation: 9603

Getting an item count with MongoDB C# driver query builder

Using the c# driver for MongoDB I can easily construct a query against which I can then add SetSkip() and SetLimit() parameters to constrict the result set to a certain size.

However I'd like to be able to know what item count of the query would be before applying Skip and Take without executing the query and loading the entire result set (which could be huge) into memory.

It looks like I can do this with MongoDB directly through the shell by using the count() command. e.g.:

 db.item.find( { "FieldToMatch" : "ValueToMatch" } ).count()

Which just returns an integer and that's exactly what I want. But I can't see a way in the documentation of doing this through the C# driver. Is it possible?

(It should be noted that we're already using the query builder extensively, so ideally I'd much rather do this through the query builder than start issuing commands down to the shell through the driver, if that's possible. But if that's the only solution then an example would be helpful, thanks.)

Cheers, Matt

Upvotes: 13

Views: 16851

Answers (2)

Flavio CF Oliveira
Flavio CF Oliveira

Reputation: 5285

I'm using the Driver 2.3.0 and now is also possible to do that like this:

...
IMongoCollection<entity> Collection = db.GetCollection<entity>(CollectionName);
var yourFilter = Builders<entity>.Filter.Where(o => o.prop == value);
long countResut = Collection.Count(yourFilter);

Upvotes: 2

Andrew Orsich
Andrew Orsich

Reputation: 53685

You can do it like this:

var server = MongoServer.Create("mongodb://localhost:27020");
var database = server.GetDatabase("someDb");

var collection = database.GetCollection<Type>("item");
var cursor = collection.Find(Query.EQ("FieldToMatch" : "ValueToMatch"));

var count = cursor.Count(); 

Some notes:

  1. You should have only one instance of server (singleton)
  2. latest driver version actually returns long count instead of int
  3. Cursor only fetches data once you iterate
  4. You can configure a lot of things like skip, take, specify fields to return in cursor before actually load data (start iteration)
  5. Count() method of cursor loads only document count

Upvotes: 19

Related Questions