【问题标题】:MongoDb cursor not returning all documents in collectionMongoDb 游标不返回集合中的所有文档
【发布时间】:2020-09-22 23:12:04
【问题描述】:

我正在尝试遍历集合中的每个文档并将它们保存到 excel 文件中。目前有 857 份文件,我已经在 Compass 中确认了这一点,但只有 756 份被退回。什么会阻止所有文件被退回?

起初我以为这与我的对象映射有关,但我恢复到 Bsondocuments 并得到相同的结果。我在这里有什么遗漏吗?

                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

【问题讨论】:

  • 查看驱动程序文档以进行迭代,如果您的代码与文档不同,请调整您的代码以匹配文档,如果您仍然有意外结果,请参考说明您正在遵循的正确迭代模式的文档。

标签: c# mongodb


【解决方案1】:

Mongo 的游标批量返回文档。您使用 MoveNext 从一个批次移动到另一个批次,然后在 Current 中处理文档。代码显示于此,但计数器 i 在每批中都重置为 1。您将需要执行以下操作:

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

或者,这样做可能更容易:

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

或者如果您没有设置异步:

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

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2021-07-06
    • 2023-03-24
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多