Jordan Morris
Jordan Morris

Reputation: 2301

In mongodb how do you do a pure update (not upsert) to replace an entire typed document?

I am trying to implement our CRUD interface using the C# MongoDB Driver. Our update method is supposed to throw an error if the record (with the same id as the passed-in model) does not exist.

I am looking for something as close as possible to this:

var result = myCollection.Update(myModel, WriteConcern.Acknowledged);
//result will have an error if a document with Id==myModel.Id did not pre-exist

I would also be happy with somthing akin to:

var query = Query<MyModel>.EQ(m => m.Id, myModel.Id);
var update = Update<MyModel>.SetDocument(myModel);
var result = myCollection.Update(query, update, WriteConcern.Acknowledged);

Is there a 'proper' way to do this? If not, what mind-boggling alternative pattern to 'CRUD my models' am I supposed to use with Mongo DB?

Is there something I can set in MongoInsertOptions to achieve this (btw, if you create your own MongoInsertOptions, how do you initialize it with the defaults which would normally be used)?

Is there some hack way to do it?

Thank you.

Upvotes: 1

Views: 2261

Answers (1)

Joe Waller
Joe Waller

Reputation: 1989

Is Replace what you are looking for?

var query = Query<MyModel>.EQ(m => m.Id, myModel.Id);
var update = Update<MyModel>.Replace(myModel);
var result = myCollection.Update(query, update, WriteConcern.Acknowledged);

http://api.mongodb.org/csharp/current/?topic=html/5e30d03f-b26a-3840-ce84-222f9804ca92.htm

And as Asya said, this will not perform an insert unless you explicitly use UpdateFlags.Upsert.

Update

In MongoDB C# Driver 2.x, replace is now achieved by a method on IMongoCollection.

await myCollection.ReplaceOneAsync(m => m.Id == myModel.Id, myModel);

Upvotes: 4

Related Questions