1 回答

TA貢獻2036條經驗 獲得超8個贊
在隊友的幫助下,這行得通。將您的模型序列化BsonDocument并傳遞BsonDocument給 MongoDB C# 驅動程序插入方法。通過這種方式,您可以使用您的 C# POCO 對象,直到您想要將其持久化到 MongoDB,然后您將其序列化為BsonDocument數組或BsonDocument保存它。因為這個復雜的模型BsonDocument[]解決了我的問題
用這個形狀和結構保存一個復雜的json模型,比下面這個形狀和結構復雜到MongoDB
//Complex json collection/array shape and structure to save as is in MongoDB
[
{
"property_1": "value_1",
"property_2": "value_2",
"property_3": {
"_some_property_1": 1,
"_some_property_2": "some_value_2",
"some_property_3": "some_value_3",
"some_property_4": "some_value_4"
},
"property_4": "value_4",
"property_5": "value_5",
"iproperty_6": "Nvalue_6",
"property_7": "value_7",
"property_8": "value_8",
"property_9": "value_9"
}
]
// This works - code snippets
/*Create a collection of C# POCO from for the json.
// My assumption is you can create C# objects/collections from complex json shape and structure
// Serialize to MongoDB BsonDocument and save*/
var models = new List<Model>{ new Model()}; // Create C# collection from json
string text = JsonConvert.SerializeObject(models);
var bsonDocument = BsonSerializer.Deserialize<BsonDocument[]>(text);
var client = new MongoClient("mongodb://localhost:27017/admin");
var database = client.GetDatabase("TestDB");
IMongoCollection<BsonDocument> collection = database?.GetCollection<BsonDocument>("TestCollection");
collection.InsertMany(bsonDocument);
- 1 回答
- 0 關注
- 295 瀏覽
添加回答
舉報