本文介绍了MongoDB InsertBatch JObject-序列化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET应用程序,并尝试插入到MongoDB中.我正在使用InsertBatch并将其传递给Newtonsoft.Json.Linq.JObject的IEnumerable

I'm using a .NET application and trying to insert to a MongoDB.I'm using InsertBatch and passing on to it IEnumerable of Newtonsoft.Json.Linq.JObject

我得到的错误:

{"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行上引发了错误.

The error is thrown at the InsertBatch line.

如果您需要任何其他信息,请提供,我只提供了我认为相关的信息.

If you need any other info please provide, I provided just what I deemed relevant.

谢谢!

推荐答案

您不能将JObject插入mongo,必须将其转换为BsonDocument

You cant insert JObject into mongo, you have to convert it to 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);

这篇关于MongoDB InsertBatch JObject-序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:57