Search code examples
c#.netmongodbmongodb-.net-driver

MongoDB for .Net simple display data example


I'm trying to display data from my MongoDB running on "mongodb://localhost:27017" to a .NET app.

This is how the Database looks.

enter image description here

This example is from the MongoDB C# Driver page on github and i can't even get pass the compile time errors:
1. I had to remove await.
2. The error i am getting now is under list

foreach statement cannot operate on variables of type 'System.Threading.Tasks.Task>' because 'System.Threading.Tasks.Task>' does not contain a public definition for 'GetEnumerator'

using MongoDB.Bson;
using MongoDB.Driver;
using System;

namespace MongoTest2
{
    class Program
    {
        public class Person
        {
            public ObjectId Id { get; set; }
            public string Name { get; set; }
        }

        static void Main(string[] args)
        {
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("test");
            var collection = database.GetCollection<Person>("messages");

            collection.InsertOneAsync(new Person { Name = "Jack" });

            var list = collection.Find(x => x.Name == "Jack")
                .ToListAsync();

            foreach (var person in list)
            {
                Console.WriteLine(person.Name);
            }
        }
    }
}

Could anyone share a simple working code snippet, or a link to a working tutorial? This is the second day and i'm still stuck on this issue.


Solution

  • You should either call synchrone methods: InsertOne() and ToList() or wait for results of asynchrone methods:

    collection.InsertOneAsync(new Person { Name = "Jack" }).Wait();
    
    var list = collection.Find(x => x.Name == "Jack")
                .ToListAsync().Result;