title: MongoDB C# Aggregate Count
body: <p>I wish to use the C# Driver (V 2.7.0) to aggregate on a collection and then count the results.</p>
  
  <p>Assuming I have an IMongoCollection col, I do the aggregate like this:</p>
  
  <pre><code>IAsyncCursor&lt;BsonDocument&gt; cursor = col.Aggregate()
      .Match(someFilterDefinition)
      .Project(someProjectionDefinition)
      .Unwind("someFieldName")
      .ToCursor();
  while (cursor.MoveNext())
  {
      foreach (BsonDocument doc in cursor.Current)
      {
          doStuff(doc);
      }
  }
  </code></pre>
  
  <p>I wish to get the number of documents returned by the aggregation. in the shell you would do something like this</p>
  
  <pre><code>db.getCollection("someCollectionName").aggregate(
      [
          { 
              "$match" : {
                  // some match filter
              }
          }, 
          { 
              "$project" : {
                  "someField" : 1
              }
          }, 
          { 
              "$unwind" : "$someField"
          }, 
          { 
              "$count" : "count"
          }
      ], 
      { 
          "allowDiskUse" : false
      }
  );
  </code></pre>
  
  <p>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.</p>
  
  <p>There is an <a href="https://mongodb.github.io/mongo-csharp-driver/2.7/apidocs/html/M_MongoDB_Driver_IAggregateFluent_1_Count.htm" rel="nofollow noreferrer">IAggregateFluent.Count()</a> Function. However it returns an IAggregateFluent
  I want an AggregateCountResult or just a simple unsigned long.</p>
  
  <p>How does one use the Aggregate.Count() function?</p>