これは古いトピックですが、投稿が行われたときと同じように今日でも関連性があり、双方向サポートの簡単なソリューションを提供するソリューションをまだ見ていません。@Maximilian Scherer コードを変更して、ドキュメントを簡単に再保存できる動的オブジェクトに変換します。
public static class MongoDynamic
{
/// <summary>
/// deserializes this bson doc to a .net dynamic object
/// </summary>
/// <param name="bson">bson doc to convert to dynamic</param>
public static dynamic ToDynamic(this BsonDocument bson)
{
var json = bson.ToJson(new MongoDB.Bson.IO.JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
dynamic e = Newtonsoft.Json.JsonConvert.DeserializeObject<ExpandoObject>(json);
BsonValue id;
if (bson.TryGetValue("_id", out id))
{
// Lets set _id again so that its possible to save document.
e._id = new ObjectId(id.ToString());
}
return e;
}
}
使用例:
// Get BsonDocument from db here
BsonDocument doc = ...
// Convert to dynamic.
var d = doc.ToDynamic();
// Lets add a none existant property.
d.Name = "test";
// Assuming you already have your collection set up
collection.Save(new BsonDocument(d));