gpt4 book ai didi

c# - 循环遍历结果集 MongoDB 3

转载 作者:可可西里 更新时间:2023-11-01 09:11:19 26 4
gpt4 key购买 nike

我有一个 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
}

推荐阅读:Introducing the 2.0 .NET Driver

关于c# - 循环遍历结果集 MongoDB 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com