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.
Asked
Active
Viewed 5.3k times
3 Answers
96
The answer is:
string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

Tom Robinson
- 8,348
- 9
- 58
- 102

Journeyman
- 10,011
- 16
- 81
- 129
59
string json = "{ 'foo' : 'bar' }";
BsonDocument document = BsonDocument.Parse(json);

Leandro Bardelli
- 10,561
- 15
- 79
- 116

m_hawk13
- 690
- 5
- 5
-
Cool.. only one error-- 'BsonDocument' does not contain a definition for 'parse -- any idea why? – Vikash Pandey Apr 13 '17 at 07:15
-
1@VikashPandey: BsonDocument.Parse is included in the new .net driver for Mongo – Rafa Feb 08 '18 at 15:35
5
Using Version 2.1 of MongoDB's .NET library
string json = "{'foo' : 'bar' }";
var document = new BsonDocument();
document.Add(BsonDocument.Parse(json));

Michael
- 239
- 3
- 9