Query guids with different binary subTypes in the same collection

88 Views Asked by At

There is a way I can query two different formats of _id?

UUID('4e519e66-751c-4ef3-9a06-3de70b95b755')

and

BinData(3, 'Zp5RThx1806aBj3nC5W3VQ==')

I have both formats in my collection.

1

There are 1 best solutions below

0
dododo On

If you have different binary sub types in your collection, then you have to use GuidRepresentationMode.V3 (see here for details):

    public void Test()
    {
        #pragma warning disable CS0618 // Type or member is obsolete
        BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
        #pragma warning restore CS0618 // Type or member is obsolete

        var client = new MongoClient();
        var db = client.GetDatabase("db");
        var coll = db.GetCollection<Entity>("coll");

        var guid3 = Guid.NewGuid();
        var guid4 = Guid.NewGuid();
        coll.InsertOne(new Entity()
        {
            BinarySubType3 = guid3,
            BinarySubType4 = guid4,
        });

        var findResult = coll.Find(i => i.BinarySubType3.CompareTo(guid3) == 0 && i.BinarySubType4.CompareTo(guid4) == 0).ToList();

        // findResult => returns 1 record
    }

    public class Entity
    {
        public ObjectId Id { get; set; }
        [BsonGuidRepresentation(GuidRepresentation.CSharpLegacy)]
        public Guid BinarySubType3 { get; set; }
        [BsonGuidRepresentation(GuidRepresentation.Standard)]
        public Guid BinarySubType4 { get; set; }
    }

This is what you will see in the shell:

> db.coll.find()

{ "_id" : ObjectId("6540aaa9870fd41f05a88851"), "BinarySubType3" : BinData(3,"ui3E5a/2KES/lqpQj748Yg=="), "BinarySubType4" : UUID("8becba1f-57b9-4ff9-a633-f78297223443") }