c# - 命令 getMore 失败:文件结束 MongoDB
问题描述
MongoCursor<BsonDocument> mongoCursor =
mongoCollection.Find(Query.And(some query))
.SetFlags(QueryFlags.NoCursorTimeout)
.SetFields(idFieldName);
int totalCount = 0;
Queue<List<long>> idBatchQueue = new Queue<List<long>>();
List<long> idBatch = new List<long>(batchSize);
foreach (BsonDocument document in mongoCursor)
{
idBatch.Add(document[idFieldName].ToInt64());
if (idBatch.Count >= batchSize)
{
idBatchQueue.Enqueue(idBatch);
totalCount += idBatch.Count;
idBatch = new List<long>(batchSize);
}
}
首先,我面临Command getMore failed: Cursor not found, cursor id:xxx error 所以为此我添加了 flag QueryFlags.NoCursorTimeout
。但现在我面临Command getMore failed: End of file in foreach
loop of mongoCursor
.
解决方案
使用异步游标 /FindAsync 它会工作
var client = new MongoClient();
IMongoDatabase db = client.GetDatabase("school");
var collection = db.GetCollection<BsonDocument>("students");
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();
}
}
}
只需测试它所提供的内容。
推荐阅读
- jquery - 如何在 fb:login-button 上应用自定义 CSS?
- android - 为什么我的代码没有读取接收方聊天?
- javascript - 从父母到孩子的反应传递
- javascript - 为什么在 Firefox 中通过 JavaScript 将背景恢复为透明会失败?
- android - 在不破坏底部活动的情况下返回一些活动
- javascript - div 不会在两次刷新之间停止自动滚动
- python - 此类是否违反单一职责原则?
- javascript - 如何在 React 中使用 React 可加载和获取组件数据(如 Next.js)进行服务器端渲染?
- c# - 如何摆脱 *.g.cs 文件的 CS4014 警告?
- sql - 需要从 nvarchar 列中选择上周