2015-11-04 139 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