[英]MongoDB C# Driver - How to InsertBatch using a List of Dictionary<string, string>
I'm new to mongodb + C# driver so forgive any naivety on my end. 我是mongodb + C#驱动程序的新手,所以请原谅我的任何天真。
I'm attempting to do a batch insert on a collection of key-value-pairs and as such my data structure is of type List<Dictionary<string,string>>
. 我正在尝试对一组键值对进行批量插入,因此我的数据结构的类型为
List<Dictionary<string,string>>
。
Here's a sample of my persistence code: 这是我的持久性代码示例:
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);
}
}
I get an error about serialization: 我收到有关序列化的错误:
MongoDB.Bson.BsonSerializationException: Serializer DictionarySerializer expected serialization options of type DictionarySerializationOptions, not DocumentSerializationOptions.
MongoDB.Bson.BsonSerializationException:序列化器DictionarySerializer预期的DictionarySerializationOptions类型的序列化选项,而不是DocumentSerializationOptions类型。
Am I missing settings? 我是否缺少设置?
EDIT: More Information 编辑:更多信息
My dictionaries are my entities. 我的字典是我的实体。 Meaning, instead of created an object to hold properties, I just dump them into a
Dictionary
. 意思是,我没有创建保存属性的对象,而是将它们转储到
Dictionary
。 From mongo documentation, it appears as this should just translate to a mongo Document
. 在mongo文档中,似乎应该将其转换为mongo
Document
。
FURTHER EDIT: Twist Question 进一步编辑:扭曲问题
I was able to get a single instance to insert by changing the using statement to: 我可以通过将using语句更改为以下内容来插入单个实例:
using (server.RequestStart(myDb))
{
foreach(var doc in documents)
collection.Insert(new BsonDocument(doc));
//var result = collection.InsertBatch(typeof(Dictionary<string, string>), documents);
}
However, my concern is performance since under a real scenario I will easily have 10k+ dictionaries. 但是,我担心的是性能,因为在实际情况下,我很容易拥有超过10k的字典。 Using this code, is the driver smart enough to batch these?
使用此代码,驱动程序是否足够聪明以进行批处理? is there a way to keep InsertBatch but accomplish the same thing?
有没有办法保留InsertBatch但完成相同的事情?
Of course, any help is much appreciated. 当然,非常感谢您的帮助。
Using your new code that uses .Insert
, the driver will not batch these inserts and you will get drastically slower performance than an InsertBatch
. 使用使用
.Insert
新代码,驱动程序将不会批处理这些插入,并且您将获得比InsertBatch
大大降低的性能。
Try this instead: 尝试以下方法:
collection.InsertBatch(documents.Select(d => new BsonDocument(d)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.