I am trying to insert a document to the mongodb database using .NET. Since the async method in the driver is not familiar to me I find difficulties in doing this.
I am calling a non-async method for a button click.
private void Button_Click(object sender, RoutedEventArgs e)
{
ConnectToMongo CM = new ConnectToMongo();
CM.CallAyncMethod();
}
From the CallAyncMethod() I'm calling the async method
public void CallAyncMethod()
{
try
{
InsertOneDocAsync().Wait();
}
catch (Exception ex)
{
Console.WriteLine($"There was an exception: {ex.ToString()}");
}
}
Here is the async method that shoud insert a document to the database
public async Task InsertOneDocAsync()
{
_client = new MongoClient("mongodb://localhost:27017");
_database = _client.GetDatabase("test");
var document = new BsonDocument
{
{ "_id", "0001" },
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
// Console.WriteLine("hello");
}
This does not insert a document to the database. This is what I get in the output console and it keeps on going
The thread 0x2424 has exited with code 0 (0x0).
The thread 0x155c has exited with code 0 (0x0).
The thread 0x26e0 has exited with code 0 (0x0).
The thread 0x131c has exited with code 0 (0x0).
When I commented all the code in the above method except // Console.WriteLine("hello"); it printed in the console. So, I guess the method has been called. Why is it not inserting the document?
How can I properly implement this?