Insert new document using InsertOneAsync (.NET Driver 2.0)

孤街醉人 提交于 2019-12-04 15:56:44

Your method should be like

 public async void Insert()
    {
         var client = new MongoClient("mongodb://localhost:27017");
        var database = client.GetDatabase("foo");
        var collection = database.GetCollection<BsonDocument>("bar");

        var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
        await collection.InsertOneAsync(document);

    }
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("foo");
var collection = database.GetCollection<BsonDocument>("bar");

var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
Task task = collection.InsertOneAsync(document);
task.Wait();

// From here on, your record/document should be in the MongoDB.

Alex

You can find in MongoDB C# driver meta file that all function declared without async which is required by await keyword and causes:

Error : The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

You can just delete the await key word. It works for me

The reason you saw nothing on the database at first was because you didn't wait (await) for Insert method to finish, which you later did by calling task.Wait(). As mentioned in comment in the link to the answer you provided, calling .Wait() like that can cause deadlock. Instead, you should call await Repository.Insert().

Check out this post about await-async http://blog.stephencleary.com/2012/02/async-and-await.html

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