I'm using the C# driver for MongoDB and trying to edit some MongoDB elements. When deserializing BSON, I'm using the [IgnoreExtraElements] tag to filter out fields I don't really care about editing. The problem is when I'm trying to serialize the elements back into the Mongo database. Instead of changing only the fields I've edited, serializing elements back overwrites the whole object.
For example, I'm changing a Word element with C# properties:
[BsonId]
public ObjectId _id;
public string word;
In MongoDB it also has the element "conjugations", which is a kind of complicated array I don't want to serialize or mess with. But when I try something similar to the below code, it blanks out the conjugations array.
MongoWord word = collection.FindOneAs<MongoWord>(Query.EQ("word","hello"));
word.word = "world";
collection.Save(word);
How can I avoid overwriting extra fields in the Json database? Right now I'm trying to write an Update.Set builder query and only update the fields I've changed using Reflection/Generics.. Is there something easy like a reverse [IgnoreExtraElements] or update setting that I'm missing here?
That's why IgnoreExtraElements must be specified manually. You are essentially opting-in to potentially losing data.
The correct way to handle this is to actually support extra elements. You can see this section in the documentation for how to do this: https://mongodb.github.io/mongo-csharp-driver/2.12/reference/bson/mapping/#supporting-extra-elements