首页 > 解决方案 > 命令 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 foreachloop of mongoCursor.

标签: c#mongodb

解决方案


使用异步游标 /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();
      }
    }
  }

只需测试它所提供的内容。


推荐阅读