Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
15 Mar 2015 1  
Solve Mongo DB Element does not match any field or property of class

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.


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here