Search code examples
c#mongodb-.net-drivernancy

MongoDb: documents with variable structure using and C#


I have a HTML form that creates documents with a dynamic structure. Here below some samples of the data inserted by the users.

A very simple document

{
"name" : "Simple element",
"notes" : "Lorem ipsum rocks",
"values" : [ 
    {
        "name" : "An array with 2 values",
        "value" : [ 100,200],
        "editable" : true
    }
]

}

And more complex document

{
"name" : "Complex element",
"notes" : "Lorem ipsum rocks",
"values" : [ 
    {
        "name" : "A text value",
        "value" : "ABCDEF",
        "editable" : true
    }, 
    {
        "name" : "A numeric value",
        "value" : 100,
        "editable" : false
    }, 
    {
        "name" : "A array of 4 values",
        "value" : [1,2,3,4],
        "editable" : false
    }, 
    {
        "name" : "A matrix 2x4",
        "value" : [[1,2,3,4],[5,6,7,8]],
        "editable" : false
    }
]

}

The documents must be saved in MongoDB using C# MongoCharp driver and NancyFX. At the moment the POST is implemented in this way but I'm not sure if this the correct way to handle object with a dynamic structure

Post["/api/docs"] = _ =>
{
  //looking for better solution
  var json = Request.Body.AsString();
  var item = BsonDocument.Parse(json);
  database.GetCollection("docs").Insert(item);
  return new Response { StatusCode = HttpStatusCode.Created };
};

but can't find a good solution for the GET method

Get["/api/docs"] = _ =>
{
  //looking for solution
};

What do you think would be the best solution for this scenario?


Solution

  • If you are just wanting to return the document from MongoDB as json try something like this

    Get["/api/docs/{category}"] = _ =>
    {
       var filterValue = _.category;
       //Search the DB for one record where the category property matches the filterValue
       var item = database.GetCollection("docs").FindOne(Query.EQ("category", filterValue))
       var json = item.ToJson();
    
       var jsonBytes = Encoding.UTF8.GetBytes(json );
       return new Response
       {
          ContentType = "application/json",
          Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length)
       };
    };