将字符串转换为MongoDB BsonDocument

Jou*_*man 52 c# mongodb mongodb-.net-driver

我有一个JSON格式的长字符串,我想将其转换为BSONDocument以插入MongoDB数据库.我该如何进行转换?我正在使用官方的C#驱动程序.

Jou*_*man 88

答案是:

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


小智 47

string json = "{ 'foo' : 'bar' }";  
BsonDocument document = BsonDocument.Parse(json);
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 6

使用 MongoDB 的 .NET 库的 2.1 版

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

  • document.Add 现在已过时。使用 document.addRange 插入。 (3认同)