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

Updating an array fails if array contains values rather than documents

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 3.0.0
    • Affects Version/s: None
    • Component/s: None
    • 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?

      Summary

      Please provide a clear and concise description of the bug.

      When updating a collection with array-update-operators such as $pull - the update fails with "InvalidCastException".

      This only occurs if the array elements are simple values (such as Int32) rather than a sub-document.

       

      
      

      _System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.Int32Serializer' to type 'MongoDB.Bson.Serialization.IBsonDocumentSerializer'.
         at MongoDB.Driver.Linq.Linq3Implementation.Translators.TranslationContext.Create(Expression expression, IBsonSerializer serializer, TranslationContextData data)
         at MongoDB.Driver.Linq.Linq3Implementation.LinqProviderAdapterV3.TranslateExpressionToField[TDocument,TField](Expression`1 expression, IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry, Boolean allowScalarValueForArrayField)
         at MongoDB.Driver.ExpressionFieldDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry, LinqProvider linqProvider, Boolean allowScalarValueForArrayField)
         at MongoDB.Driver.OperatorFilterDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry, LinqProvider linqProvider)
         at MongoDB.Driver.PullUpdateDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry, LinqProvider linqProvider)
         at MongoDB.Driver.MongoCollectionImpl`1.ConvertWriteModelToWriteRequest(WriteModel`1 model, Int32 index)
         at System.Linq.Enumerable.SelectIterator[TSource,TResult](IEnumerable`1 source, Func`3 selector)+MoveNext()
         at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
         at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
         at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation..ctor(CollectionNamespace collectionNamespace, IEnumerable`1 requests, MessageEncoderSettings messageEncoderSettings)
         at MongoDB.Driver.MongoCollectionImpl`1.CreateBulkWriteOperation(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options)
         at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
         at MongoDB.Driver.MongoCollectionImpl`1.<>c_DisplayClass30_0.<BulkWrite>b_0(IClientSessionHandle session)
         at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
         at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
         at MongoDB.Driver.MongoCollectionBase`1.<>c_DisplayClass102_0.<UpdateMany>b_0(IEnumerable`1 requests, BulkWriteOptions bulkWriteOptions)
         at MongoDB.Driver.MongoCollectionBase`1.UpdateMany(FilterDefinition`1 filter, UpdateDefinition`1 update, UpdateOptions options, Func`3 bulkWrite)
         at MongoDB.Driver.MongoCollectionBase`1.UpdateMany(FilterDefinition`1 filter, UpdateDefinition`1 update, UpdateOptions options, CancellationToken cancellationToken)
         at MongoDB.Driver.IMongoCollectionExtensions.UpdateMany[TDocument](IMongoCollection`1 collection, Expression`1 filter, UpdateDefinition`1 update, UpdateOptions options, CancellationToken cancellationToken)_

       

      Please provide the version of the driver. If applicable, please provide the MongoDB server version and topology (standalone, replica set, or sharded cluster).

       

      Driver 2.27 - but also verified on a sample of version down to 2.19 inclusive.

      Server - A volatile mongo:latest docker container from image b8df2163f9aa

       

       

      How to Reproduce

      Steps to reproduce. If possible, please include a Short, Self Contained, Correct (Compilable), Example.

       

      Just paste the following code in the program.cs of a newly created dotnet 8 vs2022 console-app project.
      Installing MongoDB.Driver nuget is required.

      Notice that if we change the array type to List<Sub> instead of List<int> the error cease to be thrown

       

       

      
      

      _// See https://aka.ms/new-console-template for more information
      using MongoDB.Bson;
      using MongoDB.Bson.Serialization.Attributes;
      using MongoDB.Driver;_

      Console.WriteLine("Hello, World!");

      var settings = MongoClientSettings.FromConnectionString("mongodb://localhost");
      // This occurs with V2 as well
      _//settings.LinqProvider = MongoDB.Driver.Linq.LinqProvider.V3;var client = new MongoClient(settings);
      var db = client.GetDatabase("Tests");
      var collection = db.GetCollection<Entity>("Test");_

      _collection.InsertOne(new Entity
      {
          Values = new List<int>

      { 1, 2, 23, 4, 5, 6 }

          //.Select(i => new Sub { Value = i }).ToList(),
      });_

      _try
      {
          collection.UpdateMany(
              e => true,
              Builders<Entity>.Update.PullFilter(
                  e => e.Values,
                  i => i < 10));
      }
      catch (Exception ex)
      {
          Console.WriteLine("Very sad!\n" + ex);
      }_

      _try
      {
          collection.UpdateMany(
              e => true,
              Builders<Entity>.Update.PullFilter(
                  e => e.Values,
                  Builders<int>.Filter.Lt(
                      x => x,
                      10)));
      }
      catch (Exception ex)
      {
          Console.WriteLine("Very sad!\n" + ex);
      }_

      Console.WriteLine();

      _[BsonIgnoreExtraElements]
      public record Entity
      {
          [BsonId]
          public ObjectId Id

      { get; set; }
          public List<int> Values { get; set; } = [];
      }_

      _public record Sub
      {
          public int Value { get; set; }

      }_

       

       

      Additional Background

      Please provide any additional background information that may be helpful in diagnosing the bug.

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            shlomi.borovitz@greenroad.com Shlomi Borovitz
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: