Sefa
Sefa

Reputation: 8992

Update all properties of object in MongoDb

I'm using the MongoDB .Net driver in my project. I want to update all of the properties of my object that is stored in MongoDB. In the documentation, update is shown like this:

var filter = Builders<BsonDocument>.Filter.Eq("i", 10);
var update = Builders<BsonDocument>.Update.Set("i", 110);

await collection.UpdateOneAsync(filter, update);

But I don't want to call the Set method for all of the properties, since there are many properties and can be many more in the future.

How can I update the whole object using the MongoDB .Net driver?

Upvotes: 28

Views: 28998

Answers (3)

bengin
bengin

Reputation: 31

If you want to update your whole BsonDocument, there is an implicit conversion from BsonDocument to UpdateDefinition.

https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/UpdateDefinition.cs

var doc = new BsonDocument() { .... }
UpdateDefinition<BsonDocument> update = doc;

Upvotes: 1

Behnam Abdy
Behnam Abdy

Reputation: 385

var update = new BsonDocument("$set", new BsonDocument(entityType.GetProperties().Where(p => p.Name != "Id").Select(p => new KeyValuePair<string, object>(p.Name, entityType.GetProperty(p.Name).GetValue(task, null)))));
var options = new UpdateOptions();
collection.UpdateOne<MyTask>(item => item.Name == "cheque", update, options);

this code uses reflection to include all properties of the given object
to the update statement, no need to manually add all properties, as u see the Id is explicitly excluded from the update statement to avoid exception.

Upvotes: 5

i3arnon
i3arnon

Reputation: 116596

You can do that with ReplaceOneAsync instead of UpdateOneAsync.

You need a filter to match the existing document (a filter with the document id is the simplest) and the new object.

Hamster hamster = ...
var replaceOneResult = await collection.ReplaceOneAsync(
    doc => doc.Id == hamster.Id, 
    hamster);

Upvotes: 54

Related Questions