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

GUID in BsonDocument ignores registered GuidSerializer

    • Type: Icon: Bug Bug
    • Resolution: Works as Designed
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: 2.14.1
    • Component/s: Serialization
    • None

      If you register a GuidSerializer, this serializer is respected for POCOs, but ignored for BsonDocuments.

      Unable to find source-code formatter for language: csharp. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      using System;
      using MongoDB.Bson;
      using MongoDB.Bson.Serialization;
      using MongoDB.Bson.Serialization.Serializers;
      using MongoDB.Driver;
      
      BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
      
      var client = new MongoClient();
      var db = client.GetDatabase("test");
      var collAsItem = db.GetCollection<Item>("guids");
      var collAsBson = db.GetCollection<BsonDocument>("guids");
      
      collAsBson.DeleteMany("{}");
      
      collAsItem.InsertOne(new Item {
          Id = Guid.NewGuid(),
          Name = "AsOrder"
      });
      
      collAsBson.InsertOne(new BsonDocument {{ "_id", Guid.NewGuid() }, { "Name", "AsBson"}});
      
      var docs = collAsBson.AsQueryable().ToList();
      foreach (var doc in docs)
      {
          Console.WriteLine($"{doc["_id"]} ({doc["Name"]})");
      }
      
      class Item
      {
          public Guid Id { get; set; }
          public string Name { get; set; }
      }
      

      The output is as follows:

      UuidStandard:0xb9d8bcca00d04b33b2d8bde43b07818e (AsOrder)
      UuidLegacy:0x12000db290a3c242b855358edade519b (AsBson)
      

      If we configure the default GUID representation (whether or not the GuidSerializer above is registered), we get the correct output:

      BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
      

      Output:

      UuidStandard:0x1e343d0ea60f4e06b463ea0d6d24840f (AsOrder)
      UuidStandard:0x1b0ad1052a4947688e35d39ab2515b88 (AsBson)
      

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

              Created:
              Updated:
              Resolved: