Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.BsonValueSerializer' to type 'MongoDB.Bson.Serialization.IBsonSerializer'
Trying to perform a Pull from a list of sub-documents in MongoDB using the C# Driver (either 2.2.4 or 2.3.0).
This is how I do the update:
FilterDefinitionBuilder<Event> filter = new FilterDefinitionBuilder<Event>();
UpdateDefinitionBuilder<Event> update = new UpdateDefinitionBuilder<Event>();
_eventRepo.FindAndUpdate(filter.Eq("EventId", eventid),
update.PullFilter("Documents", filter.Eq("DocId", docid)));
The called repository method:
public void FindAndUpdate(FilterDefinition<T> filter, UpdateDefinition<T> update)
{
_context.Collection<T>().FindOneAndUpdate(filter, update);
}
This is what the MongoDB document looks like:
{
"_id" : ObjectId("5825f74919c55e0c9c4727ee"),
"EventId" : "1234-5789",
"Documents" : [
{
"DocId" : "07c03673-c572-4f56-aaad-0edb52b3a06c",
"Name" : "test.pdf"
}
]
}
And this is the exception I get:
An exception of type 'System.InvalidCastException' occurred in MongoDB.Driver.dll but was not handled in user code
Additional information: Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.BsonValueSerializer' to type 'MongoDB.Bson.Serialization.IBsonSerializer`1[MongoDB.Bson.BsonDocument]'.
Stack trace:
at MongoDB.Driver.PullUpdateDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOneAndUpdateOperation[TProjection](FilterDefinition`1 filter, UpdateDefinition`1 update, FindOneAndUpdateOptions`2 options)
at MongoDB.Driver.MongoCollectionImpl`1.FindOneAndUpdate[TProjection](FilterDefinition`1 filter, UpdateDefinition`1 update, FindOneAndUpdateOptions`2 options, CancellationToken cancellationToken)
The exception doesn't make any sense because BsonValueSerializer
implements / inherits IBsonSerializer
(Documentation), so I would expect the Render
should be able to take a BsonValueSerializer
.
Obviously this is inside the FindOneAndReplace
method of the C# BSon driver. Is this a bug of the driver or am I doing something wrong?
I found people that do the Pull the same way (here) and it seems to work for them. I have found what looks like a very similar problem (here), but the solution and discussion couldn't help me fix mine.