Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to replace document by id

Tags:

c#

mongodb

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?


1 Answers

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.

like image 92
JohnnyHK Avatar answered Mar 24 '26 01:03

JohnnyHK