I am using the MongoDB C# driver version 2.11.0. I am aware of how GUIDs were handled differently by each driver in the past, and now there is a common standard. This isn't used by default in the C# driver for backwards compatibility reasons. The current recommendation seems to be to set the GuidRepresentation on the serializer. Either globally or for each mapped Guid property individually.
That's all fine, the problem I am facing is that queries against collections are not honoring the serialization settings, and only work properly when using the deprecated MongoDefaults setting. Documents are properly stored using the correct GuidRepresentation, but queries seem to attempt matching CSUUID rather than UUID, therefore it never matches with a document in the database.
Here's a basic class map:
public static void RegisterClassMaps()
{
BsonClassMap.RegisterClassMap<Widget>(cm =>
{
cm.MapIdProperty(w => w.Id)
.SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
cm.MapProperty(w => w.ParentId)
.SetSerializer(new GuidSerializer(GuidRepresentation.Standard));
cm.MapProperty(w => w.Name);
}
}
And here's a simple query matching a Guid and a string. The following method will always return null, as it builds the query using CSUUID rather than UUID.
private readonly IMongoCollection<Widget> _collection;
public async Task<Widget> FindByNameAsync(Guid parentId, string name)
{
var query = _collection.Find(w =>
w.ParentId == parentId &&
w.Name = name);
return await query.SingleOrDefaultAsync();
}
Using AsQueryable() rather than Find() has the same result. Both build the query using CSUUID rather than UUID.
I also tried setting the global GuidSerializer to use GuidRepresentation.Standard, but I got the same results.
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
If I change the value of the deprecated MongoDefaults property, everything works perfectly fine.
MongoDefaults.GuidRepresentation = GuidRepresantion.Standard;
Am I missing something on how I am constructing my queries? I would prefer to avoid the deprecated setting.
Had the same issue.
you need to configure the GuidRepresentationMode until it defaults to V3 in the future
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;