c# mongodb 驱动程序 groupby

c# mongodb driver groupby

我尝试执行这个查询:

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

但我有例外:

The GroupBy query operator is not supported.

我在robo中写了一个等价的请求mongo

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

它有效,但我还需要获取当前集合中的项目数。如何使用 C# mongo 驱动程序重写此查询?

我认为驱动程序只是没有实现 Linq GroupBy 方法。改用聚合框架。你可以在这里找到很好的例子 - MongoDB Aggregation Framework Examples in C#

您不需要 link 聚合框架支持随 MongoDB C# 驱动程序一起提供的任何新库。

希望对您有所帮助!

您可以使用聚合框架。此示例适用于 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;

谢谢,是我的作品范例

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