wahib
wahib

Reputation: 383

how to insert data from existing Json File To MongoDb With c#?

I Need Help , I wanna add data From Json File to MongoDb , i use this code but it give me an error : "FormatException : Cannot deserialize a 'BsonDocument' from BsonType 'Array'." :( :( this is my code

static async Task MainAsync()
    {
        var connectionString = "mongodb://localhost:27017";
        
         var client = new MongoClient(connectionString);
         IMongoDatabase database = client.GetDatabase("test");
        
         string json = File.ReadAllText("D:\\Test.json");
         //MessageBox.Show(json);
        var document = new BsonDocument();
        BsonDocument doc = BsonDocument.Parse(json);
        document.Add(BsonDocument.Parse(json));
        BsonSerializer.Deserialize<BsonDocument>(json);
        //BsonDocument document = BsonDocument.Parse(json.ToString());
         var collection = database.GetCollection<BsonDocument>("test_collection");
         await collection.InsertOneAsync(document);

And this is th code that i use it to create the JSON file :

public bool WriteJason(DataTable dt, string path)
    {
        try
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
            Dictionary<string, string> row = null;

            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, string>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName.Trim().ToString(), Convert.ToString(dr[col]));
                }
                rows.Add(row);
            }
            string jsonstring = serializer.Serialize(rows);

            using (var file = new StreamWriter(path, false))
            {
                file.Write(jsonstring);
                file.Close();
                file.Dispose();
            }
            return true;
        }
        catch { return false; }
    }

Upvotes: 0

Views: 2144

Answers (1)

dnickless
dnickless

Reputation: 10918

You need a lot less code to do that, this should be enough:

 string json = File.ReadAllText("D:\\Test.json");
 BsonDocument doc = BsonDocument.Parse(json);
 var collection = new MongoClient("mongodb://localhost:27017").GetDatabase("test").GetCollection<BsonDocument>("test_collection");
 await collection.InsertOneAsync(doc);

If that doesn't work then something is wrong with your JSON file which you would need to post here.

Upvotes: 2

Related Questions