Can't save to MongoDB from JSON or BSON.

362 views
Skip to first unread message

Niek de Gier

unread,
Apr 24, 2019, 10:48:25 AM4/24/19
to mongodb-csharp
Hi,

I'm using the C# MongoDB driver, and I struggle with a very simple thing: saving data to Mongo from JSON or BSON. I need to do some custom serialization, so I end up with a JSON or BSON (preferable JSON) string that I want to save to Mongo. However, this doesn't seem possible, which is very weird, considering JSON and BSON are the only things Mongo understands.

I only see solutions that deserialize JSON to a BsonDocument and then insert that, but that is really slow (somehow the BsonSerializer seems really unoptimized), so that is not an option.

Is there any way to directly save JSON/BSON to Mongo?

Thanks,

Niek


Sherry Ummen

unread,
Apr 25, 2019, 6:48:19 AM4/25/19
to mongodb-csharp
Hi,

Could you please tell more about your requirement ?  By the way C# driver supports saving a POCO to the database. Is that not possible in your case? Also you could still use POCO to do your stuff, For example

class MyData{
  public string JsonData{get;set;}
}

Now you can save this object to the database and you dont have to have any custom serialization logic.

Sherry

Niek de Gier

unread,
Apr 25, 2019, 8:22:15 AM4/25/19
to mongodb-csharp
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);
}
Reply all
Reply to author
Forward
0 new messages