循环遍历结果集MongoDB 3

时间:2015-11-04 17:33:58

标签: c# mongodb

我有一个应该读写MongoDB 3数据库的C#应用​​程序。不幸的是,使用MongoDB 3时,许多命名空间和方法都发生了变化,所以它有点挑战性。

以下是我的代码:

        string connectionString = Settings.Default.MongoConnectionString;
        string databaseName = Settings.Default.MongoDatabaseName;

        var client = new MongoClient(connectionString);
        var db = client.GetDatabase(databaseName);

        IMongoCollection<Post> collection = db.GetCollection<Post>("post");

        foreach (var post in collection.FindAll())
        {
            // Display to the user
        }

由于某种原因,“MongoCollection”类不再存在。如何使用新版本的MongoDB循环返回结果?

我收到以下错误:

  

'IMongoCollection'不包含'FindAll'的定义,并且没有扩展方法'FindAll'接受类型'IMongoCollection'的第一个参数可以找到

有没有人知道使用新版本循环收集的正确方法?

1 个答案:

答案 0 :(得分:6)

新的C#Driver(2.0)完全异步。为了枚举集合中的所有文档,您应该传递空过滤器并使用ToListAsync()

var filter = Builders<Post>.Filter.Empty;
foreach(var post in collection.Find(filter).ToListAsync().Result)
   // display

您也可以使用lambda而不是空过滤器:

collection.Find(p => true).ToListAsync()

当然,您可以在等待文档的情况下创建async方法,而不是阻止:

private async Task YourMethod()
{
    // ...
    var posts = await collection.Find(filter).ToListAsync();
    foreach(var post in posts)
       // display
}

推荐阅读:Introducing the 2.0 .NET Driver