Question

I have a class in C#, something like:

public class MyEntry
{
    public ObjectId Id { get; set; }
    public string SimpleHash { get; set; }
    public string GroupIdentifier { get; set; }
}

now saving this in mongo works as it should. Now I'd like to add some sub-documents to this document. The sub-document's class looks like this:

public class Detail
{
    public DateTime CreateDate { get; set; }
    public string DetailHash { get; set; }
}

I add those details to the root documents with the Push-command, like this:

collection.Update(query, Update.PushWrapped("Details", detail));

This works good so far and I have the possibility to read the MyEntry without all attached Details and I can read all/the first/the last/whichever Details I want. But my problem now is that if I change something in an MyEntry and save it, the Details-Array is completely deleted.
Is there a way to leave fields not mentioned in a class alone when updating?

Was it helpful?

Solution

You'll need to use update just like you did for the Detail. If you just use the native serialization of an entire C# class into a MongoDB collection, you'll overwrite the entire document as you've seen.

public class MyEntry
{
    public ObjectId Id { get; set; }
    public string SimpleHash { get; set; }
    public string GroupIdentifier { get; set; }
}

var update = Update<MyEntry>.Combine(
    Update<MyEntry>.Set(m => SimpleHash, "TheHash!"),
    Update<MyEntry>.Set(m => GroupIdentifier, "MyGroup"));

Then, Update the document into the collection using a query, passing the update builder object above. (Of course, you can vary the properties as needed). I like this approach better than trying to merge an object, as it means that I don't need to worry about partially loaded C# objects or accidentally removing properties from the MongoDB document because they weren't set.

I'd expect that you may need to add the attribute [BsonIgnoreExtraElements] to your MyEntry class during derserialization or the driver may throw an error when it encounters the unexpected extra data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top