Search code examples
c#mongodbmongodb-.net-driver

Retrieving data from mongodb with c#


Iam trying to find a good way to make a method that retrieve data from mongodb with the newest driver. All the guides I found are or old driver version or I cant make it work. I tried to make it with the tutorial at the mongodb site but it's just printing the results and I need to make a method that returns a list with my data. Can anyone show me a method that works?

public async Task<List<BsonDocument>> FooAsync()
{
    var Client = new MongoClient();
    var DB = Client.GetDatabase("DB");
    var collection = DB.GetCollection<BsonDocument>("Users");

    var a = await collection.Find(new BsonDocument()).ToListAsnyc();

    return (a);
}

public static List<BsonDocument> aba()
{
    var task = FooAsync();
    var result = task.Result;

    return (result);
}

Solution

  • I'm adding a method with newest MongoDB API.

     public static async Task Single()
        {
            var _client = new MongoClient(CONNECTION_STRING);
            var _database = _client.GetDatabase(DATABASE_NAME);
            var _collection = _database.GetCollection<BsonDocument>(COLLECTION_NAME);
    
            var filterBuilder = Builders<BsonDocument>.Filter;
            var filter = filterBuilder.Gt("name", "gt")
    
            var projectBuilder = Builders<BsonDocument>.Projection;
            var projection = projectBuilder.Include("name").Include("lastname").Include("age").Exclude("_id");
            var count = 0;
    
            var results = await _collection.Find(filter).Limit
                (500).Project(projection).ToListAsync();
    
            foreach(var result in results)
            {
                Console.WriteLine(result);
                count++;
            }
    
            Console.WriteLine("total count : " + count);
    
        }