问题
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