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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With