user1733952 user1733952 - 1 month ago 22
C# Question

Connect MongoDB from C# .Net

I am new to MongoDB and I am trying to connect to my client server in another system, but nothing happens when I run the code. I debugged the code and found the compiler is not passing after the line "using (var cursor = await collection.FindAsync(filter))".

private void btn_Click(object sender, EventArgs e)
{
CallMain().Wait();
}

static async Task CallMain()
{
var conString = "mongodb://215.658.326.54:2154";
var Client = new MongoClient(conString);
var DB = Client.GetDatabase("db_name");
var collection = DB.GetCollection<BsonDocument>("User");
var filter = new BsonDocument();
try
{
using (var cursor = await collection.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
foreach (var doc in cursor.Current)
{
Console.WriteLine(doc);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}


please provide me a solution for this or guide me a working code to connect to mongodb in another server and fetech data.

Answer

This is an async method you are trying to execute, so try using Task.Run to execute the method

private void btn_Click(object sender, EventArgs e)
{
    Task.Run(() => CallMain().Wait());
}

And you could use this method to retrieve your data instead of iterating a cursor

var results = await collection.Find(filter).ToListAsync();

foreach(var item in results)
{
    Console.WriteLine("whatever");
}

Also, your filter variable is an empty document, so i assume you want to retrieve all records, if so you can use this

var results = await collection.Find(x => true).ToListAsync();

Find() accepts lambda and also filter created from Builders. Look into Builders, for example

var filter = Builders<YourModel>.Filter.Eq(x => x.SomeField, "SomeValue");
var results = await collection.Find(filter).ToListAsync();

And the equivelant with lambda would be

var results = await collection.Find(x => x.SomeField == "SomeValue").ToListAsync();