MongoDB and Unity IL2CPP mobile builds

After a lot of tinkering I found a way to make the MongoDB C# Driver work with Unity IL2CPP builds (I tested it on PC and UWP builds, but I guess it works for others too)
For it to work I had to make a custom build of the driver, plus pay some attention to other details.
But before I go into a bit of detail of my findings, here’s a link to an example project that I uploaded: MongoDB IL2CPP Example Project (don’t forget to change the MongoDBTester.cs to use your instance of MongoDB)

So here’s what I did:

MongoDB Driver:
In ClientDocumentHelper.cs of the driver source is a function CreateOSDocument() which contains a section #if NET452 - I just removed that whole section and tried it out in Unity with the IL2CPP build and it solved the OPs NotSupportedException

Unity - Assembly Stripping:
The stripping process removed some code that is actually needed, which I fixed with a linker file - link.xml in the Plugins Folder of my example project.

Unity - AOT and Reflections:
The MongoDB Driver uses reflections for some things, like getting the right serializer for a collection. The AOT nature of C++ builds and the way IL2CPP works don’t mix well with that (see Unity Docs - Scripting Restrictions).
Fortunately this is easy enough to work around: If you use generic classes (like Dictionary) you need to specify the Serializer with the BsonSerializerAttribute
For constructors the same issue happens when using constructors with arguments - I just ensure that an zero argument public constructor is available for all classes that are used with MongoDB.

Unity - IPv4:
I’m not sure if this has anything to do with Unity or the MongoDB Driver, or maybe just the server why my instance of MongoDB was hosted, but I encountered a problem that my address protocol was not supported. So I wrote a workaround to use IPv4 instead.

Additional Note:
I noticed that auto-mapping of my classes did not always work. I haven’t quite figured out when and why it doesn’t work but if this happens just manually map the class with BsonClassMap.RegisterClassMap

Hope this helps, let me know if it works for you or if you encounter any other problems.