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

Serialization ignores discriminator field when checking for duplicate field names

    • Type: Icon: Bug Bug
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: Serialization
    • None

      Consider the following class definitions…

      public class Document
      {
          [BsonElement("field")]
          public string Field1 { get; set; }
          [BsonElement("field")]
          public string Field2 { get; set; }
      }
      
      public class XDocument : Document {}
      public class YDocument : Document {}
      

      If you try to insert a document, you’ll get the following expected exception.

      MongoDB.Bson.BsonSerializationException: The property 'Field2' of type 'Document' cannot use element name 'field' because it is already being used by property 'Field1'.
      

      But now change Field1 to [BsonElement("_t")] instead. It works and we insert documents that look like this:

      {"_id":{"$oid":"61fd68ac827e6acb2f0dc490"},"_t":"XDocument","_t":"field","field":null}
      

      Notice that the BSON has two _t fields, which although permitted by the BSON spec also has unspecified behaviour as noted in our documentation:

      >BSON documents may have more than one field with the same name. Most MongoDB interfaces, however, represent MongoDB with a structure (e.g. a hash table) that does not support duplicate field names. If you need to manipulate documents that have more than one field with the same name, see the driver documentation for your driver.

      As an example of this unspecified behaviour, the legacy mongo shell only displays the first _t field while Compass and mongosh only display the second.

            Assignee:
            Unassigned Unassigned
            Reporter:
            james.kovacs@mongodb.com James Kovacs
            Votes:
            0 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated: