我是 MongoDB 的新手,我使用的是 C# 驱动程序,版本:v4.0.30319: 使用 MongoDB.Bson; 使用 MongoDB.Driver;
首先抱歉,这可能是一个简单的问题,我只是无法使用正确的搜索词正确找到我需要的东西来完成这项工作。
对于我的项目。我能够连接到数据库,获取所有集合的列表,并使用 ASYNC 循环遍历其中一个集合。我遇到的问题是试图找到示例来处理简单的事情,例如计数、限制或查找/获取特定记录。
大多数示例似乎是比我正在使用的版本更旧的版本,而且我能找到的所有示例都需要 ASYNC。
这是我的一个函数,它正在工作并返回数据。
我希望能够拥有一个函数,该函数可以返回数据子集(使用查询)、获取计数和其他简单的事情。
我在集合中的数据是:
_id
RocketRequestID int
LoanRocketID int
RequestDate date
CreatedByID int
RequestXML string/xml doc
我的职能是:
static async Task<int>MainAsync()
{
int CountRecords = 0;
var client = new MongoDatabaseConnection().mongoConn();
IMongoDatabase db = client.GetDatabase("Viper");
var collection = db.GetCollection<BsonDocument>("RocketRequest");
using (IAsyncCursor<BsonDocument> cursor = await collection.FindAsync(new BsonDocument()))
{
while (await cursor.MoveNextAsync())
{
IEnumerable<BsonDocument> batch = cursor.Current;
foreach (BsonDocument document in batch)
{
Console.WriteLine(document);
Console.WriteLine();
}
}
}// end using
return CountRecords;
}// end async
同样,这可能很简单,我深表歉意,但感谢您提供的任何帮助。
最佳答案
您可以创建一个对象来映射到您的集合:
public class RocketRequest
{
public string Id { get; set; }
public int RocketRequestID { get; set; }
public int LoanRocketID { get; set; }
public DateTime RequestDate { get; set; }
public int CreatedByID { get; set; }
public string RequestXML { get; set; }
}
然后通过添加以下 using
语句尝试使用 Linq
using MongoDB.Driver.Linq;
然后您可以编写更简单的查询,例如(例如)
var collection = db.GetCollection<RocketRequest>("RocketRequest");
var count = collection.AsQueryable<Employee>()
.Count();
关于C# MongoDB 驱动程序——需要简单的代码来读取/查询集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41550343/