Mongo 带有 ObjectId 的 C# 驱动程序
Mongo C# Driver with ObjectId
我在将 Guid
转换为 BinData
时遇到问题。我知道您可以将 属性 映射到 BsonIdAttribute
,但在我的例子中,我实际上需要以 JSON 格式编写查询,并为我的 Guid
标识符添加过滤器子句。
喜欢:
mongoClient.UpdateMany(
new JsonFilterDefinition<UserUnreadCounter>($"{{ \"Counters.EntityId\": {{ $eq: '{myGuid.ConvertToBinData()}' }} }}"),
new JsonUpdateDefinition<UserUnreadCounter>("{ $inc: { \"Counters.$.Count\": 1 } }"));
如何转换?它是否只裁剪 Guid
的十六进制表示的前 24 个符号?
How can I convert it? Does it just crop the first 24 symbols of hex
representation of the Guid?
不完全是。它实际上是 Guid 字节(由 MongoDB.Bson.GuidConverter.ToBytes(guid, GuidRepresentation.CSharpLegacy)
返回)转换为 Base64 字符串。下面是执行此类转换的 C# 代码:
var str = Convert.ToBase64String(MongoDB.Bson.GuidConverter.ToBytes(guid, GuidRepresentation.CSharpLegacy));
例如,对于 Guid {a6f262e1-2b58-4c90-89f2-f12c4fad19b1}
,它将导致 4WLyplgrkEyJ8vEsT60ZsQ==
。
我在将 Guid
转换为 BinData
时遇到问题。我知道您可以将 属性 映射到 BsonIdAttribute
,但在我的例子中,我实际上需要以 JSON 格式编写查询,并为我的 Guid
标识符添加过滤器子句。
喜欢:
mongoClient.UpdateMany(
new JsonFilterDefinition<UserUnreadCounter>($"{{ \"Counters.EntityId\": {{ $eq: '{myGuid.ConvertToBinData()}' }} }}"),
new JsonUpdateDefinition<UserUnreadCounter>("{ $inc: { \"Counters.$.Count\": 1 } }"));
如何转换?它是否只裁剪 Guid
的十六进制表示的前 24 个符号?
How can I convert it? Does it just crop the first 24 symbols of hex representation of the Guid?
不完全是。它实际上是 Guid 字节(由 MongoDB.Bson.GuidConverter.ToBytes(guid, GuidRepresentation.CSharpLegacy)
返回)转换为 Base64 字符串。下面是执行此类转换的 C# 代码:
var str = Convert.ToBase64String(MongoDB.Bson.GuidConverter.ToBytes(guid, GuidRepresentation.CSharpLegacy));
例如,对于 Guid {a6f262e1-2b58-4c90-89f2-f12c4fad19b1}
,它将导致 4WLyplgrkEyJ8vEsT60ZsQ==
。