Vladislav Qulin
Vladislav Qulin

Reputation: 1942

Mongo C# Driver with ObjectId

I'm having troubles with converting the Guid into BinData. I know that you can just map the property with BsonIdAttribute, but in my case I actually need to write the query in JSON format with filter clause for my Guid identifier.

Like:

mongoClient.UpdateMany(
    new JsonFilterDefinition<UserUnreadCounter>($"{{ \"Counters.EntityId\": {{ $eq: '{myGuid.ConvertToBinData()}' }} }}"),
    new JsonUpdateDefinition<UserUnreadCounter>("{ $inc: { \"Counters.$.Count\": 1 } }"));

How can I convert it? Does it just crop the first 24 symbols of hex representation of the Guid?

Upvotes: 1

Views: 853

Answers (1)

CodeFuller
CodeFuller

Reputation: 31282

How can I convert it? Does it just crop the first 24 symbols of hex representation of the Guid?

Not exactly. It's actually Guid bytes (as returned by MongoDB.Bson.GuidConverter.ToBytes(guid, GuidRepresentation.CSharpLegacy)) converted to Base64 string. Here is C# code that does such conversion:

var str = Convert.ToBase64String(MongoDB.Bson.GuidConverter.ToBytes(guid, GuidRepresentation.CSharpLegacy));

For example, for Guid {a6f262e1-2b58-4c90-89f2-f12c4fad19b1} it will result to 4WLyplgrkEyJ8vEsT60ZsQ==.

Upvotes: 1

Related Questions