2015-11-04 124 views
3

我有一个C#应用程序应该读取和写入MongoDB 3数据库。不幸的是,在MongoDB 3中,似乎很多命名空间和方法都发生了变化,所以它有点具有挑战性。循环遍历结果集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' does not contain a definition for 'FindAll' and no extension method 'FindAll' accepting a first argument of type 'IMongoCollection' could be found

有谁知道通过使用新版本的集合的正确方法循环?

回答

5

新的C#驱动程序(2.0)是完全异步的。为了枚举集合中的所有文件,你应该通过空的过滤器,并使用ToListAsync()

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

您还可以使用拉姆达的,而不是空的过滤器:

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

+0

谢谢谢尔盖。这两个建议都很好用。 –

+0

如果您的收藏品是1,000万件物品会怎样?它会为这份文件分配一份清单吗?如果是的话,是否有一个去避免这种情况? – tigrou

+1

使用'AsQueryable()'似乎是解决方案: 'foreach(collection.AsQueryable()中的var item)'就像一个魅力一样,即使集合包含很多项目。 – tigrou