c# mongodb driver groupby

I try to execute this query:

MongoCollection<AnalyticsClicks> dbCollection =
DetermineCollectionName<AnalyticsClicks>();
                 var query = from c in dbCollection.AsQueryable()
                             where c.UserId == userId && c.CampaignId == campaignId
                             select new { c.Email, c.Link };


var res = query.GroupBy(x => x.Email, b => b.Link).Count();

but I have exception: The GroupBy query operator is not supported. I wrote a equivalent request in the robomongo

db.analyticsClicks.aggregate(
{ $match: { UserId: 4790, CampaignId: 92093}},
{ $group : {
        "_id" : { 
            "Email" : "$Email",
            "Link" : "$Link",
        } 
    }
})

it's work, but I also need to get the count items in the current collection. How can I rewrite this query to c# mongo driver?

You can use aggregation framework. This example is for MongoDB.Driver 2.0

var collection = database.GetCollection<Item>("Item");
var result = await collection
      .Aggregate()
      .Group(new BsonDocument
      {
           {
               "_id", new BsonDocument
               {
                   {"Email", "$Email"},
                   {"Link", "$Link"},
               }
           }
      })
      .Group(new BsonDocument
      {
           { "_id", "_id" },
           {"count", new BsonDocument("$sum", 1)}
      })
      .FirstAsync();
var count = result["count"].AsInt32;

Thank you, it is my work example

MongoCollection<AnalyticsClicks> dbCollection = DetermineCollectionName<AnalyticsClicks>();

            var match = new BsonDocument 
            { 
                { 
                    "$match", 
                    new BsonDocument {{"UserId", userId}, {"CampaignId", campaignId}} 
                } 
            };

            var group = new BsonDocument 
            { 
                { "$group", 
                    new BsonDocument 
                    { 
                        { "_id", new BsonDocument {{"Email", "$Email" }, {"Link", "$Link"}, }}, 
                    } 
                } 
            };

            AggregateArgs pipeline = new AggregateArgs()
            {
                Pipeline = new[] { match, group }
            };
            var result = dbCollection.Aggregate(pipeline);
            return Convert.ToInt32(result.Count());

I think the driver just doesn't implement the Linq GroupBy method. Use aggregate framework instead. You can find good examples here -MongoDB Aggregation Framework Examples in C#

You don't need to link any new libraries the support for the aggregation framework goes with MongoDB C# driver.

Hope it helps!

What Others Are Reading