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

为君一笑 提交于 2021-02-06 03:31:07

问题


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


回答1:


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
            });
        }
}



回答2:


I was trying to save some dynamic object associated to a ProcessID, the dynamic object it's totally "dynamic", sometimes it can be one property with some arbitrary data and name, sometimes it can be a 100 properties with totally arbitrary names for each property. In fact, it's an object coming from an Angular 5 app that generates a dynamic form from (surprise) some JSON object. My "base" class, the one that get inserted into mongo it's like this:

public class MongoSave {

    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    public string Id { get; set; }        
    public int ProcessID { get; set; }
    public BsonDocument DynamicData { get; set; }

}

On my first attempt the DynamicData property was type object, the controller method received everything ok, assign the incoming object to the class but when saving the object to mongo the values for DynamicData were lost. I was getting only the property names. Tried to use the BsonSerializeannotation in my class but with no success.

Researching a little bit i discovered that BsonDocument has a Parse method similar to javascript that parse a string containing an object description, so... i posted an object like this to my controller:

{
    "ProcessID": 987,
    "DynamicData": {
        "name": "Daniel",
        "lastName": "Díaz",
        "employeeID": 654
    }
{

A few things here, i'm sending via Insomnia (a Postman alternative) this JSON to the API. In real world i'll be sending this object via Angular so i have to be sure to apply JSON.stringify(obj) to be sure that the JSON object it's ok (don't know for sure if the Angular HttpClient post objects as stringified JSON or as JS objects (i'll test that). Changed my controller action to use the Parse method and the DynamicData C# generic object to string like this:

[HttpPost("~/api/mongotest/save")]
public async Task<IActionResult> PostObjectToMongo (MongoSaveDTO document) {

    MongoSave mongoItem = new MongoSave() {
        ProcessID = document.ProcessID,
        DynamicData = BsonDocument.Parse(document.DynamicData.ToString())
    };

    await _mongoRepo.AddMongoSave(mongoItem);

    return Ok();
}

The MongoSaveDTO it's the same as MongoSave without the BsonIdproperty and instead of BsonDocument i'm using C# generic object type and everything saves like a charm.



来源:https://stackoverflow.com/questions/25536306/mongodb-c-sharp-how-to-save-arbitrary-json-document-as-dynamic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!