c#mongodb driver groupby

时间:2015-06-16 16:44:09

标签: c# mongodb mongodb-.net-driver

我尝试执行此查询:

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

但我有例外:

  

不支持GroupBy查询运算符。

我在robomongo中写了一个等效的请求

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

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

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

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

您不需要将任何新库链接到聚合框架的支持与MongoDB C#驱动程序。

希望它有所帮助!

答案 2 :(得分:1)

谢谢,这是我的工作示例

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