Home > Mobile >  How must a json look to force mongodb to BinData subtype 4
How must a json look to force mongodb to BinData subtype 4

Time:06-24

I'm using the c# driver MongoDB.Driver 2.16.0 I'm trying to insert pure json. I want the _id to be used as the new UUID type aka BinData subtype 4. But I get only subtype 3 or pure string.

var testColl = db.GetCollection<BsonDocument>("test");
var testJson = "[{'_id':CSUUID('609e26f6-dbad-4dba-ba37-4e35f0e348ec'),'name':'Data1'},{'_id':CSUUID('609e26f6-dbad-4dba-ba37-4e35f0e348ff'),'name':'Data2'}]";
testColl.InsertMany(BsonSerializer.Deserialize<BsonDocument[]>(testJson));

I tried '_id':'609e26f6-dbad-4dba-ba37-4e35f0e348ec' which results in a string.
I tried '_id':UUID('609e26f6-dbad-4dba-ba37-4e35f0e348ec') which rusults in subtype 3.
And the example code also results in subtype 3.

How must the json look to make a subtype 4?

CodePudding user response:

You have the following options:

  1. Configure BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;. In this case, you will work with subTypes specified in the document (or via attributes see the doc in the end). If it's CSUUID - then subType is 3, UUID - 4.

  2. Configure GuidSerialization.Unspecified. For example during collection creating:

    db.GetCollection<BsonDocument>(
        "coll", 
        new MongoCollectionSettings() { GuidRepresentation = GuidRepresentation.Unspecified});
    

this case is similar to #1 where we get used subType from a document, but only for a particular collection

  1. Configuring GuidSerialization.Standard to force using this particular subType for a collection regardless a subType provided in the document:

    var coll = db.GetCollection<BsonDocument>("coll", new MongoCollectionSettings() { GuidRepresentation = GuidRepresentation.Standard});
    var testJson = "[{'_id':CSUUID('609e26f6-dbad-4dba-ba37-4e35f0e348ec'),'name':'Data1'},{'_id':CSUUID('609e26f6-dbad-4dba-ba37-4e35f0e348ff'),'name':'Data2'}]";
    coll.InsertMany(BsonSerializer.Deserialize<BsonDocument[]>(testJson)); // inserted subType is 4 (UUID/Standard)
    

You also can configure GuidRepresentation globally like: BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;. In this case you will force using this representation by default everywhere (for GuidRepresentationMode.V2 which is default mode)

You can find details here

  • Related