title: MongoDB Aggregate function to C#
body: <p>this has been bugging me all night.</p>
  
  <p>I have the following MongoDb function that returns the top searches in a collection including there count</p>
  
  <pre><code>db.search.aggregate([
      {
          $match: {
              keywords: { $not: {$size: 0} }
          }
      },
      { $unwind: "$term" },
      {
          $group: {
              _id: {$toLower: '$term'},
              count: { $sum: 1 }
          }
      },
      {
          $match: {
              count: { $gte: 2 }
          }
      },
      { $sort : { count : -1} },
      { $limit : 100 }
  ]);
  </code></pre>
  
  <p>I am trying to move this to a C# function and I am getting the error :</p>
  
  <blockquote>
    <p>MongoDB.Driver.MongoCommandException: 'Command aggregate failed: A
    pipeline stage specification object must contain exactly one field..'</p>
  </blockquote>
  
  <p>Here is my C# version, can anyone see what I am missing?</p>
  
  <pre><code>var pipeline = new BsonDocument[] {
  new BsonDocument
  {
      {
          "$match",
          new BsonDocument {{"keywords", new BsonDocument {{"$not", new BsonDocument {{"$size", 0}}}}}}
      }
  },
  new BsonDocument {{"$unwind", "$term"}},
  new BsonDocument
  {
      {
          "$group", new BsonDocument
          {
              {"_id", new BsonDocument {{"$toLower", "$term"}}},
              {
                  "count", new BsonDocument
                  {
                      {"$sum", 1}
                  }
              }
          }
      }
  },
  new BsonDocument
  {
      {
          "$match", new BsonDocument
          {
              {"count", new BsonDocument {{"$gte", 2}}}
          }
      },
      {
          "$sort", new BsonDocument
          {
              {"count", -1}
          }
      },
      {"$limit", 100}
  }
  };
  
  var result = collection.Aggregate&lt;BsonDocument&gt;(pipeline).ToListAsync();
  Console.WriteLine(result);
  </code></pre>