我有一个 C# 应用程序,它应该读取和写入 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
有谁知道使用新版本循环遍历集合的正确方法吗?
最佳答案
新的 C# 驱动程序 (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
}
关于c# - 循环遍历结果集 MongoDB 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528368/