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);
        }
    }

首先,我面对的是getmore命令失败:找不到游标,游标id:xxx错误,因此我添加了flagQueryFlags.NoCursorTimeout
但现在我面临着getmore失败的命令:在foreachmongoCursor循环中结束文件。

最佳答案

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

就像它给你的一样测试。

09-25 17:18