[CSHARP-4040] Serialization ignores discriminator field when checking for duplicate field names Created: 04/Feb/22  Updated: 31/Mar/22

Status: Backlog
Project: C# Driver
Component/s: Serialization
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Unknown
Reporter: James Kovacs Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to SERVER-6439 Duplicate fields at the same level sh... Backlog
Epic Link: Quick Wins

 Description   

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.


Generated at Wed Feb 07 21:47:01 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.