0

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);
}
ronmar
  • 39
  • 2
  • 13

1 Answers1

0

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

    }
trallallalloo
  • 592
  • 1
  • 9
  • 25
  • And let's say I want to call this method and I want it to return a list my method will be like public static async Task> Single(). How can I call this method and get the list? @vedat – ronmar Oct 20 '15 at 14:28
  • change return type of method and create a list instance. After, add documents into the list in foreach. Then return list. – trallallalloo Oct 20 '15 at 14:40
  • for more information about using list in async method, you can look at this topic. http://stackoverflow.com/questions/27309716/async-await-returning-tasklistt-instead-of-listt-on-calling-aync-method – trallallalloo Oct 20 '15 at 14:45