[CSHARP-2030] Add allowDuplicateElementNames to BsonDocument.Parse Created: 10/Aug/17  Updated: 22/Jan/18  Resolved: 22/Jan/18

Status: Closed
Project: C# Driver
Component/s: API
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: Artem Zinenko Assignee: Robert Stam
Resolution: Won't Fix Votes: 0
Labels: neweng
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

In my application I have to work with jsons which contains duplicate names:

{ "a" : "qqq", "a" : "qqq" }

It is very convenient to parse json by BsonDocument.Parse, but it fails on json containing duplicate names:

System.InvalidOperationException : Duplicate element name 'a'.

It will be cool if we'll add a method with signature:

BsonDocument Parse(string json, bool allowDuplicateElementNames)



 Comments   
Comment by Robert Stam [ 22/Jan/18 ]

I appreciate your need to parse documents with duplicate elements, but as we wish to discourage (though not prohibit) use of duplicate elements in general I don't think we should any way to make it easier to use them. The risk is that someone using the API will misinterpret the fact that we made it easy as implicit endorsement of using duplicate elements.

Probably the best approach for you in your application is to encapsulate parsing with duplicate elements allowed in a small static helper class, so you can write code like:

var document = BsonDocumentAllowDuplicates.Parse(json);
var ok = BsonDocumentAllowDuplicates.TryParse(json, out BsonDocument document);

Keep in mind that if you decide to insert documents with duplicate element names into the database the behavior is undefined.

Comment by Artem Zinenko [ 12/Sep/17 ]

BsonDocuments with duplicate element names are not recommended.

I know, but I have to work with them: I get these jsons from another application (not my) and that application couldn't be changed.
So in my case I have only two options:

  1. Do all the work myself: parse json and remove elements with duplicate names.
  2. Add allowDuplicateElementNames option to BsonDocument.Parse.
Comment by Robert Stam [ 07/Sep/17 ]

BsonDocuments with duplicate element names are not recommended.

For example, inserting a document with duplicate element names into a MongoDB collection is not really well defined. Under some update operations one of the duplicate element names could be subsequently dropped.

What is your reason for wanting to do so?

Comment by Artem Zinenko [ 10/Aug/17 ]

PR: https://github.com/mongodb/mongo-csharp-driver/pull/288

Comment by Artem Zinenko [ 10/Aug/17 ]

I'll create a PR soon.

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