【问题标题】:MongoDB C# Driver - How to InsertBatch using a List of Dictionary<string, string>MongoDB C# 驱动程序 - 如何使用 Dictionary<string, string> 列表进行 InsertBatch
【发布时间】:2012-08-18 00:40:06
【问题描述】:

我是 mongodb + C# 驱动程序的新手,所以请原谅我的任何天真。

我正在尝试对一组键值对进行批量插入,因此我的数据结构类型为 List&lt;Dictionary&lt;string,string&gt;&gt;

这是我的持久性代码示例:

public void Persist(string collectionName, List<Dictionary<string, string>> documents)
{
  string connectionString = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_KEY].ConnectionString;
  MongoServer server = MongoServer.Create(connectionString);
  MongoCredentials credentials = new MongoCredentials("MYUser", "MyPassword");
  MongoDatabase myDb = server.GetDatabase("myDb", credentials);

  var collection = myDb .GetCollection(collectionName);

  using (server.RequestStart(myDb ))
  {
    var result = collection.InsertBatch(documents);
  }
}

我收到关于序列化的错误:

MongoDB.Bson.BsonSerializationException:序列化程序 DictionarySerializer 预期的序列化选项 输入 DictionarySerializationOptions,而不是 DocumentSerializationOptions。

我是否缺少设置?

编辑:更多信息

我的字典就是我的实体。意思是,我没有创建一个对象来保存属性,而是将它们转储到Dictionary 中。从 mongo 文档看来,这应该只是转换为 mongo Document

进一步编辑:扭曲问题

我可以通过将 using 语句更改为:

using (server.RequestStart(myDb))
  {
    foreach(var doc in documents)
      collection.Insert(new BsonDocument(doc));
    //var result = collection.InsertBatch(typeof(Dictionary<string, string>), documents);
  }

但是,我关心的是性能,因为在实际情况下,我很容易拥有 10k+ 字典。使用此代码,驱动程序是否足够聪明来批量处理这些?有没有办法保留 InsertBatch 但完成同样的事情?

当然,非常感谢任何帮助。

【问题讨论】:

    标签: c# mongodb serialization mongodb-.net-driver


    【解决方案1】:

    使用使用.Insert 的新代码,驱动程序将不会批处理这些插入,您将获得比InsertBatch 慢得多的性能。

    试试这个:

    collection.InsertBatch(documents.Select(d => new BsonDocument(d)));
    

    【讨论】:

    • 正是我想要的!谢谢!
    猜你喜欢
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2015-08-01
    相关资源
    最近更新 更多