Search code examples
mongodbc#-4.0bson

not able to save documents in mongodb c# with .Net driver 2.0


I want to save the document in a collection my method is as below but it is not saving at all.

internal static void InitializeDb()
    {
        var db = GetConnection();
        var collection = db.GetCollection<BsonDocument>("locations");
        var locations = new List<BsonDocument>();
        var json = JObject.Parse(File.ReadAllText(@"..\..\test_files\TestData.json"));
        foreach (var d in json["locations"])
        {
            using (var jsonReader = new JsonReader(d.ToString()))
            {
                var context = BsonDeserializationContext.CreateRoot(jsonReader);
                var document = collection.DocumentSerializer.Deserialize(context);
                locations.Add(document);
            }
        }
        collection.InsertManyAsync(locations);
    }

If I made async and await then it runs lately, I need to run this first and then only test the data.


Solution

  • For future reference, wait() at end of async method work like synchronously

    internal static void InitializeDb()
    {
        var db = GetConnection();
        var collection = db.GetCollection<BsonDocument>("locations");
        var locations = new List<BsonDocument>();
        var json = JObject.Parse(File.ReadAllText(@"..\..\test_files\TestData.json"));
        foreach (var d in json["locations"])
        {
            using (var jsonReader = new JsonReader(d.ToString()))
            {
                var context = BsonDeserializationContext.CreateRoot(jsonReader);
                var document = collection.DocumentSerializer.Deserialize(context);
                locations.Add(document);
            }
        }
        collection.InsertManyAsync(locations).wait();
    }