MongoDB C# - how to save arbitrary JSON document as dynamic type?

Turp picture Turp · Aug 27, 2014 · Viewed 17.3k times · Source

I am trying to write a general purpose Web Api controller that will allow me to save a JSON document to a collection WITHOUT specifying a C# type. I've tried to condense the code down to the essentials:

public class PassThroughController : ApiController
{
    [Route("api/mongodb/{collection}")]
    public void Post(string collection, dynamic document)
    {
        const string connectionString = "mongodb://localhost";

        var client = new MongoClient(connectionString);
        var db = client.GetServer().GetDatabase("SampleDb");
        var mongoCollection = db.GetCollection(collection);

        mongoCollection.Save(document,
            new MongoInsertOptions
            {
                WriteConcern = WriteConcern.Acknowledged
            });
        }
}

I'm trying to post a simple document:

{ id: "2112", name: "Rush" }

But no matter what I send to the method, I get an error similar to this: "Save can only be used with documents that have an Id."

We've attempted a number of different properties for Id (Id, id, _id) but they all result in a similar issue.

Any ideas?

Thanks

Answer

Turp picture Turp · Aug 29, 2014

With the help of a co-worker, I figured out a solution:

public class PassThroughController : ApiController
{
    [Route("api/mongodb/{collection}")]
    public void Post(string collection, HttpRequestMessage message)
    {
        const string connectionString = "mongodb://localhost";

        var client = new MongoClient(connectionString);
        var db = client.GetServer().GetDatabase("SampleDb");
        var mongoCollection = db.GetCollection(collection);

        var json = message.Content.ReadAsStringAsync().Result;
        var document = BsonSerializer.Deserialize<BsonDocument>(json);

        mongoCollection.Save(document,
            new MongoInsertOptions
            {
                WriteConcern = WriteConcern.Acknowledged
            });
        }
}