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

BsonDocument constructor fails to copy documents with duplicate element names

    • Type: Icon: New Feature New Feature
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: BSON
    • Labels:
      None
    • 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?

      The following code fails:

      var doc = new BsonDocument() { AllowDuplicateNames = true };

      doc.Add("x", 1);

      doc.Add("x", 2);

      var doc2 = new BsonDocument(doc); // throws

       

      This is because the parameter is treated as an IEnumerable<BsonElement>. This can be fixed by adding a new constructor:

      /// <summary>
      /// Initializes a new instance of the BsonDocument by coping elements from another BsonDocument.
      /// </summary>
      /// <param name="document">The document whose elements will be copied</param>

      public BsonDocument(BsonDocument document)
      {
        if (document == null)
        {
          throw new ArgumentNullException("document");
        }

        _allowDuplicateNames = document.AllowDuplicateNames;
        AddRange(document);
      }

       

      This could be ambiguous if somebody tried to pass a RawBsonDocument or LazyBsonDocument, so two additional constructors may be useful:

      /// <summary>
      /// Initializes a new instance of the BsonDocument by coping elements from a LazyBsonDocument.
      /// </summary>
      /// <param name="document">The document whose elements will be copied</param>

      public BsonDocument(LazyBsonDocument document) : this((BsonDocument)document) { }

      /// <summary>
      /// Initializes a new instance of the BsonDocument by coping elements from a RawBsonDocument.
      /// </summary>
      /// <param name="document">The document whose elements will be copied</param>

      public BsonDocument(RawBsonDocument document) : this((BsonDocument)document) { }

            Assignee:
            boris.dogadov@mongodb.com Boris Dogadov
            Reporter:
            admilazz Adam Milazzo
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: