Search code examples
c#.netjsonmongodbmongodb-.net-driver

Cannot convert BsonArray to BsonDocument in c#


I have my Json string as

string myjson = "[
{
    "col1": "1",
    "col2": "2",
    "col3": "3"
},
{
    "col1": "4",
    "col2": "5",
    "col3": "6"
},
{
    "col1": "7",
    "col2": "8",
    "col3": "9"
}]";

Problem is : When i am creating bson document it is showing

Cannot convert BsonArray to BsonDocument

This is how I'm creating the BsonDocument :

BsonDocument doc = BsonSerializer.Deserialize<BsonDocument>(myjson);

What should i do?


Solution

  • BsonDocument doc = new BsonDocument();
    BsonArray array = BsonSerializer.Deserialize<BsonArray>(myjson);
    doc.Add(array);
    

    I didn't try it but it should work.

    Edit:

            string myjson1 = "{ 'col1': '1', 'col2': '2', 'col3': '3'}";
            string myjson2 = "{ 'col1': '4', 'col2': '5', 'col3': '6'}";
            string myjson3 = "{'col1': '7', 'col2': '8', 'col3': '9'}";
    
            BsonArray arr = new BsonArray();
            arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson1));
            arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson2));
            arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson3));
    

    or simply have a values element inside the document like this:

    string myjson = "[ { 'col1': '1', 'col2': '2', 'col3': '3'},{ 'col1': '4', 'col2': '5', 'col3': '6'},{'col1': '7', 'col2': '8', 'col3': '9'}]";    
    var doc = new BsonDocument {
                        { "values", BsonSerializer.Deserialize<BsonArray>(myjson) }
                    };
    

    The best that I could do is this.