【问题标题】:c# mongodb batch insert时间:2019-04-01 标签:c#mongodbbatch insert
【发布时间】:2014-08-12 11:14:51
【问题描述】:

我想将 csv 文件导入 MongoDB。 csv 文件有 3,00,000 条记录和 10 个字段。我找不到 MongoDB 文档中描述的 InsertBatch 方法的好教程。使用 insert() 方法一条一条地插入记录,耗时超过 15 分钟。

【问题讨论】:

    标签: c# .net mongodb


    【解决方案1】:

    this 对您有帮助吗?

    MongoCollection<BsonDocument> books;
    
    List<BsonDocument> batch = new List<BsonDocument>();
    
    using (CsvReader reader = new CsvReader("users.csv"))
    {
        batch.add(
            new BsonDocument {
                { "field1", reader["field1"] },
                { "field2", reader["field2"] }
            }),
    };
    books.InsertBatch(batch.ToArray());
    

    【讨论】:

    • 没关系,但是如何动态创建BsonDocument,即读取CSV文件?
    • 有很多.NET库可以读取csv文件,like this one.
    • 我编辑了我的帖子,为您提供我链接的 CSV 库的示例。
    • 我收到以下错误use of unsigned local variable 'books'
    【解决方案2】:

    感谢 elpaulo 的帮助。我修改了代码并尝试使用 bulkinsert 测试代码。这是完整的代码

    var mongo = new MongoClient("mongodb://10.44.4.59");
    MongoServer server = mongo.GetServer();
    
    MongoDatabase test = server.GetDatabase("server_info");
    var category = test.GetCollection("test_collection");
    
    List<BsonDocument> batch = new List<BsonDocument>();
    
    for (int i = 0; i < 300000; i++)
    {
       batch.Add(
           new BsonDocument {
               { "field1", 1 },
               { "field2", 2 },
               { "field3", 3 },
               { "field4", 4 }
            });
    }
    category.InsertBatch(batch);
    

    插入这么多数据大约需要 30 秒。再次感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2016-10-23
      • 2011-01-31
      • 2013-04-11
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多