Insert new document using InsertOneAsync (.NET Driver 2.0)

Hana picture Hana · Apr 13, 2015 · Viewed 15.7k times · Source

In the older .Net API version :

MongoClient client = new MongoClient();
var server = client.GetServer();
var db = server.GetDatabase("foo");
var collection = db.GetCollection<BsonDocument>("bar");
var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
collection.Save(document);

It worked.

When i use new .Net Driver 2.0 :

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);

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'.

Refs :

Introducing the 2.0 .NET Driver

Reading and Writing

I want to ask how to insert a new document using .Net Driver 2.0. Thanks.

[Update 1] I tried to implement :

public class Repository
{
    public static async Task 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);
    }
}

static void Main(string[] args)
{            
       Task tsk = Repository.Insert();
       tsk.Wait();
       Console.WriteLine("State: " + tsk.Status);            
}

Result : WaitingForActivation. Nothing changed in database. Please help me!

[Update 2 (Solved)] : add tsk.Wait(); It worked ! Thanks this post : How would I run an async Task method synchronously?

Answer

Dhaval Patel picture Dhaval Patel · Apr 13, 2015

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);

    }