Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-5540

Exception when using AsQueryable().Last()

    • Type: Icon: Bug Bug
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 3.2.1
    • Component/s: Linq
    • None
    • Dotnet Drivers
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      Summary

      There seems to be a bug in how the query is translated when using AsQueryable().Last() or AsQueryable().LastOrDefault(). It will fail with an exception: `FormatException: Element '_last' does not match any field or property of class MyClass.`

      If we look at the code, you can see that it uses an aggregation:

      ```csharp
      pipeline = pipeline.AddStage(
      AstStage.Group(
      id: BsonNull.Value,
      fields: AstExpression.AccumulatorField("_last", AstUnaryAccumulatorOperator.Last, AstExpression.RootVar)),
      pipeline.OutputSerializer);
      ```

      So the last object of the collection ends up wrapped inside a "_last" field of another object.

      Looks like you need to add another stage here to return the object itself without the wrapper:
      ```csharp
      AstStage.ReplaceRoot(AstExpression.GetField(AstExpression.RootVar, "_last"))
      ```

      How to Reproduce

      Connect to the server using MongoDB.Driver and try executing AsQueryable().Last() on a collection.

      Additional Information

      Looks like an easy fix to me. I could make a PR.

            Assignee:
            ferdinando.papale@mongodb.com Ferdinando Papale
            Reporter:
            schernyae@gmail.com Sergey Chernyaev
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              None
              None
              None
              None