Is there a way to replace on the mongodb a document by ID? Instead of finding the document by some property, I'd like to replace it on the ID. With a document specified with the same ID. Is this possible?
You can use ReplaceOne or ReplaceOneAsync to do this:
var filter = Builders<BsonDocument>.Filter
.Eq("_id", new ObjectId("561674ef936e327431cbd349"));
var newdoc = new BsonDocument
{
// _id is optional here, but if it's present, it must match the replaced doc's _id
{"_id", new ObjectId("561674ef936e327431cbd349")},
{"label", "new value"}
};
var result = collection.ReplaceOne(filter, newdoc);
See the docs on the topic here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With