Mongo C # Fluent Aggregation Pipeline Group Anonymous Type Key Exception

I am using the new Fluent Aggregation Pipeline conference in vgen 10gen Mongo C # driver v2, but I am experiencing an exception when trying to group more than one field (example code below).

The exception that is thrown is ...

Command aggregation failure: exception: the aggregation field of the month group must be defined as an expression inside the object.

I can get this to work by creating a type for my group key, but would prefer to use an anonymous type, since the type I will need to create will not serve other purposes.

var agg = db.GetCollection<Order>("orders").Aggregate();

var project = agg.Project(o => new {o.Value
                                  , o.Product
                                  , Month = o.Date.Month
                                  , Year = o.Date.Year});

var group = project.Group(
  key => new { key.Month, key.Product},
  g => new OrderSummary {Month = g.Key.Month
                        ,Product = g.Key.Product
                        , TotalSales = g.Sum(o => o.Value)});

var result =  group.ToListAsync().Result;

For reference...

public class Order : Entity
{

    public DateTime Date { get; set; }

    public string Product { get; set; }

    public double Value { get; set; }
}
public class OrderSummary
{
    public string Product { get; set; }
    public int Month { get; set; }
    public int Year { get; set; }
    public double TotalSales { get; set; }

}

The team created by the free API ...

{  "aggregate" : "Order", 
   "pipeline" : [ 
     { "$project" : { "Value" : "$Value", "Product" : "$Product", "Month" : { "$month" : "$Date" }, "Year" : { "$year" : "$Date" }, "_id" : 0 } }
   , { "$group" : { 
       "_id" : { "Month" : "$Month", "Product" : "$Product" }
      , "Month" : "$Month"
      , "Product" : "$Product"
      , "TotalSales" : { "$sum" : "$Value" } } }]
, "cursor" : { } }
+4
source share
1

, , . , _id, . , Month Product _id, . :

var group = project.Group(
    key => new { key.Month, key.Product },
    g => new
    {
         MonthAndProduct = g.Key,
         TotalSales = g.Sum(o => o.Value)
    });

, , , , .

var project = group.Project(x => new OrderSummary
{
     Month = x.MonthAndProduct.Month, 
     Product = x.MonthAndProduct.Product, 
     TotalSales = x.TotalSales
});

, , , / jira.mongodb.org CSHARP.

, Craig

+8

All Articles