Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all properties of object in MongoDb

Tags:

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?

like image 883
Sefa Avatar asked Jun 17 '15 13:06

Sefa


People also ask

How do you update all elements in an array in MongoDB?

To update multiple elements, use []. The[] is an all positional operator indicating that the update operator should modify all elements in the specified array field.


1 Answers

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); 
like image 55
i3arnon Avatar answered Oct 11 '22 02:10

i3arnon