MongoDB InsertBatch JObject - Serialization error

时光怂恿深爱的人放手 提交于 2021-01-28 14:07:03

问题


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

The error i'm getting:

{"Serializer DictionarySerializer<String, JToken> expected serialization options of type DictionarySerializationOptions, not DocumentSerializationOptions."}

My code is:

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);
}

The error is thrown at the InsertBatch line.

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

Thanks!


回答1:


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);


来源:https://stackoverflow.com/questions/27471220/mongodb-insertbatch-jobject-serialization-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!