I have a complex nested JSON data structure below saved in a file data.json. The data structure is reducted but this will apply to all json data structures. I read and deserialize the json into C# model. I then write the object/data to MongoDB using MongoDB C# client driver How would you save this COMPLEX object/data/model to MongoDB?
Complex nested data structure, data.json file
[
{
"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"
}
]
C# ASP.NET Web Api Demo Code
namespace DemoWebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public void Get()
{
var models = CreateModels();
var client = new MongoClient("mongodb://localhost:27017/admin");
var database = client.GetDatabase("TestDB");
/*
THIS DOES NOT WORK
IMongoCollection<MODEL> collection = database?.GetCollection<MODEL>("TestCollection");
collection.InsertMany(models);
*/
}
private static List<Model> CreateModels()
{
List<Model> models = new List<Model>();
foreach (string file in Directory.GetFiles("<path/to/data.json>", "*", SearchOption.AllDirectories))
{
using (var fileStream = File.OpenRead(file))
{
using (var sr = new StreamReader(fileStream))
{
string json = sr.ReadToEnd();
var data = JsonConvert.DeserializeObject<List<Model>>(json);
models.AddRange(data);
}
}
}
return models;
}
}
}
C# Model
namespace DemoWebApi.Models
{
public class Model
{
[BsonExtraElements, BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments), JsonExtensionData]
public IDictionary<string, object> _additionalData;
}
}