65

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.

3 Answers 3

99

The answer is:

string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Cool.. only one error-- 'BsonDocument' does not contain a definition for 'parse -- any idea why?
@VikashPandey: BsonDocument.Parse is included in the new .net driver for Mongo
5

Using Version 2.1 of MongoDB's .NET library

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

1 Comment

document.Add is obsolete now. Use document.addRange insted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.