Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update all document fields except specified ones in mongodb

I present a simple model:

public class UserDocument
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public string DisplayName { get; set; }

    public List<string> Friends { get; set; }
}

I am using the latest C# driver which has the ability to replace a document using a C# object which will automatically update all its fields. Problem is I want to update all fields except for the user friends, because it's a field containing the object relations to other documents. Of course I can manually update each field of the ones I want to get updated, which here are just two.

But this example is simple just to make my point. In reality the fields are much more and it would be harder to update each field. That would require a single line for each one to use the Set operator. Also, newly-added fields would have to be supported in the same way as opposed to updating to automatically just works.

Is there a way to achieve that - automatically update all fields with just specifying a list of excluded fields?

like image 387
Ceco Avatar asked May 27 '15 21:05

Ceco


People also ask

How do you update a specific field in MongoDB?

To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.


1 Answers

There is no way, using the provided builders to have a "blacklist" update which excludes only specific fields.

You can query the old document, copy the old values of these fields to the new instance and then replace it entirely in the database.

You can also generate such an update command by iterating over the fields using reflection.

But the MongoDB driver doesn't offer such a query built in.

like image 69
i3arnon Avatar answered Oct 09 '22 10:10

i3arnon