13

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

2 Answers 2

19

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
Sign up to request clarification or add additional context in comments.

4 Comments

Ah okay. So the data isn't loaded into memory until you actually start to iterate through the items? In other words I can call .Count() against the cursor without getting all the documents as well?
Cool - that's the key bit of information I needed, thanks. Would be useful to know if this is spelled out in documentation anywhere but in the meantime, have a tick :)
@MattThrower: I don't know, i don't really read a lot of docs. It is simpler for me to read the source code :)
I personnaly prefer collection.Count(Query.EQ("FieldToMatch", "ValueToMatch")); instead of Find().
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.