【问题标题】:Aggregate field must be defined as an expression inside an object error聚合字段必须定义为对象错误中的表达式
【发布时间】:2017-05-05 20:52:46
【问题描述】:

尝试将以下 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", 
}

【问题讨论】:

  • 请提供样本数据。这应该有助于重现错误。
  • @AxxE 更新了样本数据。谢谢。
  • 嗨,你能显示对象过滤器吗?

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


【解决方案1】:

group 方法不知道 g.Key.ProductType 所以我们必须在 project 方法中投影 key 的元素。

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

【讨论】:

  • 嗨,你能显示对象过滤器吗?
猜你喜欢
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 2017-12-11
相关资源
最近更新 更多