必须将聚合字段定义为对象错误内的表达式

时间:2017-05-05 20:52:46

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

尝试将mongodb聚合查询下面的端口移植到c#,但收到错误 -

  

命令聚合失败:组聚合字段'ProductType'必须   被定义为对象内的表达式。

有关c#代码有什么问题的想法吗?

db.collectionName.aggregate([
        { $match: activeTrial},
        {  $project: {_id:1, CustomerType: 1, ProductType: 1} },
        { $group: {_id: {"cust": "$CustomerType", "prod" : "$ProductType"}, count: {$sum: 1}}},
          ]).toArray()

collectionName.Aggregate()
                .Match(filter)
                .Project(x => new {x.CustomerType, x.SubscriptionId, x.ProductType})
                .Group(x => new { x.ProductType, x.CustomerType }, g => new ActiveTrialsByProduct()
                {
                    ProductType = g.Key.ProductType,
                    CustomerType = g.Key.CustomerType,
                    ActiveTrials = g.Count()
                }).ToList();

这是收藏..

{  
    "CustomerType" : "CustA",   
    "ProductType" : "ProdA", 
}
{  
    "CustomerType" : "CustA",   
    "ProductType" : "ProdB", 
}
{  
    "CustomerType" : "CustA",   
    "ProductType" : "ProdB", 
}
{  
    "CustomerType" : "CustA",   
    "ProductType" : "ProdA", 
}

1 个答案:

答案 0 :(得分:1)

组方法不了解g.Key.ProductType,因此我们必须在项目方法中投影键的元素。

collectionName.Aggregate()
                .Match(filter)
                .Project(x => new {x.CustomerType, x.ProductName, x.SubscriptionId })
                .Group(x => new { x.ProductName, x.CustomerType }, g => new 
                {
                    Id = g.Key,
                    ActiveTrials = g.Count()
                })
                .Project(x => new ActiveTrialsByProduct()
                {
                    CustomerType = x.Id.CustomerType,
                    Product = x.Id.ProductName,
                    ActiveTrials = x.ActiveTrials
                }).ToList();