Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 works, but I also need to get the count of items in the current collection. How can I rewrite this query using C# mongo driver?

like image 833
Veronika Kostenko Avatar asked Jun 16 '15 16:06

Veronika Kostenko


2 Answers

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;
like image 195
rnofenko Avatar answered Oct 06 '22 13:10

rnofenko


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());
like image 4
Veronika Kostenko Avatar answered Oct 06 '22 12:10

Veronika Kostenko