3

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;
        }
    }
4
  • Was there any errors thrown? Commented Dec 12, 2018 at 16:55
  • No error is thrown. The data is not saved in the MongoDB database. Commented Dec 12, 2018 at 17:17
  • @Brian Rogers I have added the answer. Thanks Commented Dec 14, 2018 at 20:46
  • Thank you! I appreciate the effort to clean this up. Commented Dec 14, 2018 at 20:49

1 Answer 1

2

With the help of team mates, this works. Serialize your model to BsonDocument and pass the BsonDocument to the MongoDB C# driver insert method. This way you can work with your C# POCO object until when you want to persist it to MongoDB then you serialize to BsonDocument array or BsonDocument and save it. For this complex model BsonDocument[] solves my problem

Save a complex json model with this shape and structure, complex than this shape and structure below to 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);
Sign up to request clarification or add additional context in comments.

1 Comment

What if you have a Model, but 1 property is going to be an object and you don't know what values it will contain? I only that it will be an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.