Convert string into MongoDB BsonDocument

C#MongodbMongodb .Net-Driver

C# Problem Overview


I have a long string in JSON format, and I want to convert it into a BSONDocument for insertion into a MongoDB database. How do I do the conversion? I'm using the official C# driver.

C# Solutions


Solution 1 - C#

The answer is:

string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

Solution 2 - C#

string json = "{ 'foo' : 'bar' }";  
BsonDocument document = BsonDocument.Parse(json);

Solution 3 - C#

Using Version 2.1 of MongoDB's .NET library

string json = "{'foo' : 'bar' }";
var document = new BsonDocument();
document.Add(BsonDocument.Parse(json));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJourneymanView Question on Stackoverflow
Solution 1 - C#JourneymanView Answer on Stackoverflow
Solution 2 - C#m_hawk13View Answer on Stackoverflow
Solution 3 - C#MichaelView Answer on Stackoverflow