我正在使用 .NET 应用程序并尝试插入到 MongoDB。 我正在使用 InsertBatch 并将 Newtonsoft.Json.Linq.JObject 的 IEnumerable 传递给它
我遇到的错误:
{"Serializer DictionarySerializer<String, JToken> expected serialization options of type DictionarySerializationOptions, not DocumentSerializationOptions."}
我的代码是:
private void InsertItemsToMongo(IEnumerable<JObject> list)
{
MongoClient = new MongoClient("mongodb://localhost:27017");
var myDb = mongo.GetServer().GetDatabase("MyDatabase");
if (!myDb.CollectionExists("MyStuff");
myDb.CreateCollection("MyStuff");
MongoCollection<JObject> myCollection = myDb.GetCollection<JObject>("MyStuff");
myCollection.InsertBatch(list);
}
错误在 InsertBatch 行引发。
如果您需要任何其他信息,请提供,我仅提供了我认为相关的信息。
谢谢!
最佳答案
你不能将JObject插入mongo,你必须将它转换为BsonDocument
var bsonlist = new List<BsonDocument>();
foreach (var obj in list)
{
bsonlist.Add(BsonDocument.Parse(obj));
}
var myCollection = database.GetCollection("MyStuff");
var doc = BsonArray.Create(bsonlist);
myCollection.InsertBatch(doc);
关于c# - MongoDB InsertBatch JObject - 序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471220/