Solve Mongo DB Element Does Not Match Any Field or Property of Class - CodeProject

:

Introduction

Due to non schema nature of mongodb collection, one collection may contain a distinct number of fields. It's not recommended though, it's possible to contain different number of fields due to business requirements. So for example, say we have a collection “Client”, under which there are 2 documents. The second document lacks 1 field “City”. So while binding back to POCO via C# driver, we get an exception “Element does not match any field or property of class”.

sample-1

Solution

When a BSON document is deserialized back to POCO, the name of each element is used to look up a matching field or property in the class map, when deserializer does not find the mapping property it throws an exception, that we have in this scenario. If we want to ignore those extra properties, there are two possible ways, during deserialization or during initialization of the BsonClassMap. I prefer this while I do the mapping, I live to keep my POCO clean.

sample-2

As you can see, the above code block, SetIgnoreExtraElements methods is used to specify inside mapping to ignore extra elements from BSON document.

map.SetIgnoreExtraElements(true);

That’s it, now you can work with your POCO more easily.