4

I wish to use the C# Driver (V 2.7.0) to aggregate on a collection and then count the results.

Assuming I have an IMongoCollection col, I do the aggregate like this:

IAsyncCursor<BsonDocument> cursor = col.Aggregate()
    .Match(someFilterDefinition)
    .Project(someProjectionDefinition)
    .Unwind("someFieldName")
    .ToCursor();
while (cursor.MoveNext())
{
    foreach (BsonDocument doc in cursor.Current)
    {
        doStuff(doc);
    }
}

I wish to get the number of documents returned by the aggregation. in the shell you would do something like this

db.getCollection("someCollectionName").aggregate(
    [
        { 
            "$match" : {
                // some match filter
            }
        }, 
        { 
            "$project" : {
                "someField" : 1
            }
        }, 
        { 
            "$unwind" : "$someField"
        }, 
        { 
            "$count" : "count"
        }
    ], 
    { 
        "allowDiskUse" : false
    }
);

and you would get a document (or no document) with a single "count" field, having an int64 value of the number of elements from the stage before it.

There is an IAggregateFluent.Count() Function. However it returns an IAggregateFluent I want an AggregateCountResult or just a simple unsigned long.

How does one use the Aggregate.Count() function?

1 Answer 1

13

Instead of just appending Count(), which gets you an aggregation stage, you must finish the aggregation with either .ToCursor or .FirstOrDefault or similar. The FirstOrDefault returns the AggregateCountResult, which has the Count property.

ulong count = col.Aggregate()
    .Match(someFilterDefinition)
    .Project(someProjectionDefinition)
    .Unwind("someFieldName")
    .Count()
    .FirstOrDefault() // returns AggregateCountResult
    .Count();         // returns ulong
Sign up to request clarification or add additional context in comments.

2 Comments

It should be .FirstOrDefault().Count; without brackets. In current version (2.9.1) it also returns a long instead of ulong.
Be careful: When there are no entries to count then .Count() will return no element. Therefor .FirstOrDefault() is null and .Count will throw a NullReferenceException.

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.