William Carr
William Carr

Reputation: 21

Insert json string into mongoDB c# driver v2.4.3

I get a json result from an javascript api query(no problems, valid json) and I would like to insert it into mongoDb.

My json string:

    {"data":[{"accessible_wheelchair":true,"address":"181 Washington St","attire":"casual","category_ids":[344],"category_labels":[["Social","Food and Dining","Ice Cream Parlors"]],"country":"us","cuisine":["Ice Cream","Frozen Yogurt","Bagels","Deli","Donuts"],"factual_id":"403b11e4-c383-4305-8ba1-96aa6339eaba","hours":{"sunday":[["11:00","22:00"]],"saturday":[["11:00","22:00"]],"tuesday":[["11:00","22:00"]],"friday":[["11:00","22:00"]],"thursday":[["11:00","22:00"]],"wednesday":[["11:00","22:00"]],"monday":[["11:00","22:00"]]},"hours_display":"Open Daily 11:00 AM-10:00 PM","latitude":42.707169,"locality":"Boxford","longitude":-71.066385,"meal_deliver":false,"name":"Benson Ice Cream","open_24hrs":false,"parking":true,"payment_cashonly":false,"postcode":"01921","price":1,"rating":4.5,"region":"MA","tel":"(978) 352-2911","website":"http://bensonsicecream.com/","wifi":false},{"accessible_wheelchair":true,"address":"256 Georgetown Rd","address_extended":"Unit 5","attire":"casual","category_ids":[363],"category_labels":[["Social","Food and Dining","Restaurants","Pizza"]],"country":"us","cuisine":["Pizza","Cafe","Sandwiches","Subs"],"factual_id":"05e95c81-1125-447b-a500-84e0d380540d","fax":"(314) 423-3377","hours":{"sunday":[["11:00","21:00"]],"saturday":[["11:00","22:00"]],"tuesday":[["11:00","21:00"]],"friday":[["11:00","22:00"]],"thursday":[["11:00","21:00"]],"wednesday":[["11:00","21:00"]],"monday":[["11:00","21:00"]]},"hours_display":"Mon-Thu 11:00 AM-9:00 PM; Fri-Sat 11:00 AM-10:00 PM; Sun 11:00 AM-9:00 PM","latitude":42.697431,"locality":"Boxford","longitude":-70.988191,"meal_cater":true,"meal_deliver":true,"meal_takeout":true,"name":"Boxford House of Pizza","open_24hrs":false,"parking":true,"payment_cashonly":false,"postcode":"01921","price":1,"rating":4.5,"region":"MA","tel":"(978) 887-2212","website":"http://www.bostonrestaurantgroup.com","wifi":false}],"included_rows":2,"total_row_count":2}

I post the json string(arrayString) to a C# controller with ajax.

    $.ajax({
        url: '/Place/CreateMany',
        type: 'POST',
        contentType: 'application/json;',
        data: JSON.stringify(arrayString),
        success: function (valid) {
            if (valid) {
                alert("success ");
            } else {
                alert("failure" + arrayString);
            }
        }
    });

The controller errors out with a vague 500 internal server error.

    [HttpPost] 
    public ActionResult CreateMany(string arrayString)
    {

        JObject jObject = JObject.Parse(arrayString);
        JToken placeObj = jObject["data"];

        foreach (string data in placeObj)
        {
            //have a working model defined called PlaceModel
            //works with insertOne
            var document = BsonSerializer.Deserialize<PlaceModel>(data);

            //I am using a working repo(InsertPlace) that uses MongoDB method "insertOne"
            //I would like to use a new repo that uses "insertMany"
            this._places.InsertPlace(document);
        }
        return RedirectToAction("List", _places.SelectAll());
    }

Not sure what to do to go from json string array of more than one to a single object of my model type (PlaceModel)

This is my first post, so please go easy, but I am open to suggestions.

Upvotes: 1

Views: 3207

Answers (1)

William Carr
William Carr

Reputation: 21

Veeram was correct. I needed to use BSON serialization not JSON.

    [HttpPost] 
    public void CreateMany(string jsonString)
    {
        //sets up mongo connection, DB and collection
        var Client = new MongoClient();
        var DB = Client.GetDatabase("PlacesDb");
        var collection = DB.GetCollection<PlaceModel>("PlaceCollection");

        if (jsonString != null)
        {
            IList<PlaceModel> documents = BsonSerializer.Deserialize<IList<PlaceModel>>(jsonString);
            collection.InsertMany(documents);
        }
    }

On the ajax post, I had to add datatype: 'json' and pass my json string as an array jsonString:jsonString with jsonString in [] brackets

self.saveToMongoDB = function (jsonString) {
    $.ajax({
        url: '/Place/CreateMany',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: JSON.stringify({ jsonString: jsonString }),
        success: function (valid) {
            if (valid) {
                alert("success " + jsonString);
            } else {
                alert("failure" + jsonString);
            }
        }
    });
};

Upvotes: 1

Related Questions