Hi,
I have hierarchical class structure which is basically a big tree where all the nodes derive from a base class that has an Id property. When I want to save a node to MongoDB, it is impossible to save the whole tree to mongo (which it does by default), since a fully expanded node could easily become more than the 16mb limit (also, this is really slow, even without the limit).
So my solution is to replace all references to objects that inherit from the base class with their respective Id property. This is why I need the custom serialization, because I do want my class structure to remain intact. However, after I serialized my objects, I have to deserialize to BsonDocument, and put that into Mongo, which seems a little unnecessary, since you can easily save JSON directly to mongo via the mongo shell, so I was wondering if the C# driver also supports directly saving from JSON.
Code snippet:
public static async Task Insert<T>(string collectionName, IEnumerable<T> batch)
{
IdMapper idMapper = new IdMapper();
string json = Newtonsoft.Json.JsonConvert.SerializeObject(batch, idMapper);
var documents = BsonSerializer.Deserialize<IEnumerable<BsonDocument>>(json);
IMongoCollection<BsonDocument> collection = GetCollection<BsonDocument>(collectionName);
await collection.InsertManyAsync(documents);
}