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

Exception when using AsQueryable().Last()

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 3.4.0
    • Affects Version/s: 3.2.1
    • Component/s: LINQ
    • None
    • Fully Compatible
    • Dotnet Drivers
    • Not Needed
    • Hide

      1. What would you like to communicate to the user about this feature?
      2. Would you like the user to see examples of the syntax and/or executable code and its output?
      3. Which versions of the driver/connector does this apply to?

      Show
      1. What would you like to communicate to the user about this feature? 2. Would you like the user to see examples of the syntax and/or executable code and its output? 3. Which versions of the driver/connector does this apply to?
    • 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:
              Resolved: