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

后端 未结 2 742
小蘑菇
小蘑菇 2021-02-04 12:05

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 co

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 12:59

    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(json);
    
            mongoCollection.Save(document,
                new MongoInsertOptions
                {
                    WriteConcern = WriteConcern.Acknowledged
                });
            }
    }
    

提交回复
热议问题