Store dynamic JSON data in MongoDB

Viewed 385

My client service generates a dataset which includes a dynamic field. This is some anonymous object with unstructured data. I need to transmit this via POST request to my storage service.

Now I want to store the data in the same way I receive it. The problem is, that my storage service parses it as JObject which when stored in MongoDB results in odd data. In the MongoDB Compass I cannot see the values of my dataset anymore.

Following test data is being sent currently:

{
    "sessionId" : "202C25C1-DE25-499B-B4F1-1D46FA169A02",
    "timestamp" : "5/6/2005 09:34:42 PM",
    "type" : "request",
    "data" : {
        "testField1" : 120,
        "testField2" : "Test Value",
        "testField3" : [ "value1", "value2" ]
    }
}

And this is what I get from MongoDB:

{
    "_id": {
        "$oid": "6076bceebc1aec06799826dd"
    },
    "SessionId": {
        "$binary": "wSUsICXem0m08R1G+haaAg==",
        "$type": "3"
    },
    "Timestamp": {
        "$date": "2005-05-06T19:34:42.000Z"
    },
    "Type": 0,
    "Data": {
        "_t": "Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed",
        "_v": {
            "testField1": {
                "_t": "JValue",
                "_v": []
            },
            "testField2": {
                "_t": "JValue",
                "_v": []
            },
            "testField3": {
                "_t": "JArray",
                "_v": [
                    {
                        "_t": "JValue",
                        "_v": []
                    },
                    {
                        "_t": "JValue",
                        "_v": []
                    }
                ]
            }
        }
    }
}

EDIT: Furthermore storing this data results in exceptions when trying to retrieve the data from the database. MongoDB cannot deserialize JToken objects as it has no access to some methods/constructors.

It's pretty much garbage. I tried it with storing the JSON as string, but then MongoDB does not store it as actual JSON object but as actual string and thus breaks the intention of document-based storage:

{
    "_id": {
        "$oid": "6076bc8fbc1aec06799826a5"
    },
    "SessionId": {
        "$binary": "wSUsICXem0m08R1G+haaAg==",
        "$type": "3"
    },
    "Timestamp": {
        "$date": "2005-05-06T19:34:42.000Z"
    },
    "Type": 0,
    "Data": "{\"testField1\":120,\"testField2\":\"Test Value\",\"testField3\":[\"value1\",\"value2\"]}"
}

Is there any solution how I can store a dynamic object in just the same way? I cannot simply deserialize it into a dynamic object since that would result in an JObject as it actually derives from the interface for dynamics. But as said MongoDB can't handle these objects correctly.

1 Answers
Related