简体   繁体   English

MongoDb 游标不返回集合中的所有文档

[英]MongoDb cursor not returning all documents in collection

I'm trying to iterate over every document in a collection and save them to an excel file.我正在尝试遍历集合中的每个文档并将它们保存到一个 excel 文件中。 Currently there are 857 documents and I have confirmed this in Compass, but only 756 are being returned.目前有 857 个文件,我已经在 Compass 中确认了这一点,但只有 756 个被退回。 What would stop all the documents from being returned?什么会阻止所有文件被退回?

At first I thought it was to do with my object mapping, but I reverted back to Bsondocuments and I get the same result.起初我认为这与我的对象映射有关,但我又回到了 Bsondocuments 并且得到了相同的结果。 Is there something I am missing here?有什么我在这里想念的吗?

                var db = client.GetDatabase("database");
                var collection = db.GetCollection<BsonDocument>("collection");
                var filter = new BsonDocument();
                using (var cursor = collection.Find(filter).ToCursor())

                    while (cursor.MoveNext())
                    {
                        int i = 1;
                        foreach (var doc in cursor.Current)

                        {
                            ;
                            sheet.Cells["A" + i.ToString()].Value = doc.ToString();
                            i++;
                            Console.WriteLine("Documents found: " + i);
Documents found: 757

Mongo's cursor returns documents in batches. Mongo 的游标批量返回文档。 You move from batch to batch using MoveNext and then processing the documents in Current.您可以使用 MoveNext 从一个批次移动到另一个批次,然后在 Current 中处理文档。 The code appears to this, but the counter i is reset to 1 on every batch.代码出现于此,但计数器 i 在每批上重置为 1。 You will want to do something like:你会想要做这样的事情:

            var db = client.GetDatabase("database");
            var collection = db.GetCollection<BsonDocument>("collection");
            var filter = new BsonDocument();
            using (var cursor = collection.Find(filter).ToCursor()){
                int i = 1;
                while (cursor.MoveNext())
                {                        
                    foreach (var doc in cursor.Current)

                    {
                        ;
                        sheet.Cells["A" + i.ToString()].Value = doc.ToString();
                        i++;                     
                    }
                }
                Console.WriteLine("Documents found: " + i);
             }

Alternately it may be easier to do:或者,这样做可能更容易:

    int i = 1;
    await cursor.ForEachAsync(doc => {
      sheet.Cells["A" + i.ToString()].Value = doc.ToString()
      i++;
    });
    Console.WriteLine("Documents found: " + i);

or if you aren't setup for async:或者如果您没有设置异步:

    int i = 1;
    cursor.ForEachAsync(doc => {
      sheet.Cells["A" + i.ToString()].Value = doc.ToString()
      i++;
    }).Wait();
    Console.WriteLine("Documents found: " + i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM