MongoDB InsertBatch JObject - 序列化错误

本文关键字:序列化 错误 JObject InsertBatch MongoDB | 更新日期: 2023-09-27 18:34:09

我正在使用.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);
}

错误在插入批处理行引发。

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

谢谢!

MongoDB InsertBatch JObject - 序列化错误

你不能将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);