Search code examples
c#mongodbmongodb-.net-driver

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?


Solution

  • 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());