title: Mongo C# Driver 2.0 Aggregate Group exception
body: <p>I am attempting to select the latest record in a collection for each group according to a multi-field key, using the fluent Aggregate interface:</p>
  
  <pre><code>        var matches = await Collection.Aggregate()
              .Match(x =&gt; x.EffectiveDate &gt;= minEffectiveDate)
              .SortByDescending(x =&gt; x.LastUpdate)
              .Group(key =&gt; new { key.EffectiveDate, key.ProductOid, key.InstrumentParentOid, key.ComponentOid, key.EventSummary }, g =&gt; g.First())
              .ToListAsync();
  </code></pre>
  
  <p>However, I get the following exception:</p>
  
  <pre><code>System.InvalidCastException occurred
    HResult=-2147467262
    Message=Unable to cast object of type 'MongoDB.Driver.Linq.Expressions.SerializationExpression' to type 'System.Linq.Expressions.MethodCallExpression'.
    Source=MongoDB.Driver
    StackTrace:
     at MongoDB.Driver.Linq.Processors.GroupSerializationInfoBinder.GetBodyFromSelector(MethodCallExpression node)
     at MongoDB.Driver.Linq.Processors.GroupSerializationInfoBinder.GetAggregationArgument(MethodCallExpression node)
     at MongoDB.Driver.Linq.Processors.GroupSerializationInfoBinder.VisitMethodCall(MethodCallExpression node)
     at MongoDB.Driver.Linq.Translators.AggregateProjectionTranslator.BindSerializationInfo(SerializationInfoBinder binder, LambdaExpression node, IBsonSerializer parameterSerializer)
     at MongoDB.Driver.Linq.Translators.AggregateProjectionTranslator.TranslateGroup[TKey,TDocument,TResult](Expression`1 idProjector, Expression`1 groupProjector, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
     at MongoDB.Driver.IAggregateFluentExtensions.GroupExpressionProjection`3.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
     at MongoDB.Driver.AggregateFluent`2.&lt;&gt;c__DisplayClass1`1.&lt;Group&gt;b__0(IBsonSerializer`1 s, IBsonSerializerRegistry sr)
     at MongoDB.Driver.DelegatedPipelineStageDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
     at MongoDB.Driver.PipelineStageDefinition`2.MongoDB.Driver.IPipelineStageDefinition.Render(IBsonSerializer inputSerializer, IBsonSerializerRegistry serializerRegistry)
     at MongoDB.Driver.PipelineStagePipelineDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
     at MongoDB.Driver.MongoCollectionImpl`1.&lt;AggregateAsync&gt;d__7`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at MongoDB.Driver.IAsyncCursorSourceExtensions.&lt;ToListAsync&gt;d__14`1.MoveNext()
  </code></pre>
  
  <p>Ok. So it doesn't like the IEnumerable extension method for some reason. So I try extracting the LINQ extension method:</p>
  
  <pre><code>        var matches = await Collection.Aggregate()
              .Match(x =&gt; x.EffectiveDate &gt;= minEffectiveDate)
              .SortByDescending(x =&gt; x.LastUpdate)
              .Group(key =&gt; new { key.EffectiveDate, key.ProductOid, key.InstrumentParentOid, key.ComponentOid, key.EventSummary }, g =&gt; g)
              .ToListAsync();
          return matches.Select(x =&gt; x.First());
  </code></pre>
  
  <p>But:</p>
  
  <pre><code>System.InvalidCastException occurred
    HResult=-2147467262
    Message=Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.ArraySerializer`1[SPMO.Providers.Audit.Messages.ProductAdjustmentAuditDataDb]' to type 'MongoDB.Bson.Serialization.IBsonSerializer`1[System.Linq.IGrouping`2[&lt;&gt;f__AnonymousType0`5[System.Nullable`1[System.DateTime],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.String],SPMO.Providers.Audit.Messages.ProductAdjustmentAuditDataDb]]'.
    Source=MongoDB.Driver
    StackTrace:
         at MongoDB.Driver.Linq.Translators.AggregateProjectionTranslator.TranslateGroup[TKey,TDocument,TResult](Expression`1 idProjector, Expression`1 groupProjector, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
         at MongoDB.Driver.IAggregateFluentExtensions.GroupExpressionProjection`3.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
         at MongoDB.Driver.AggregateFluent`2.&lt;&gt;c__DisplayClass1`1.&lt;Group&gt;b__0(IBsonSerializer`1 s, IBsonSerializerRegistry sr)
         at MongoDB.Driver.DelegatedPipelineStageDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
         at MongoDB.Driver.PipelineStageDefinition`2.MongoDB.Driver.IPipelineStageDefinition.Render(IBsonSerializer inputSerializer, IBsonSerializerRegistry serializerRegistry)
         at MongoDB.Driver.PipelineStagePipelineDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
         at MongoDB.Driver.MongoCollectionImpl`1.&lt;AggregateAsync&gt;d__7`1.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at MongoDB.Driver.IAsyncCursorSourceExtensions.&lt;ToListAsync&gt;d__14`1.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  </code></pre>
  
  <p>My plan B is just to forget about Aggregate, do a simple Find() and then do a GroupBy() in vanilla LINQ, but I would like to get this working on the DB as it will be more efficient.</p>