In the official documentation of mongodb they mention upserts, so it would be really nice to write an upsert command instead of:
if (_campaignRepo.Exists(camp)) { _campaignRepo.DeleteByIdAndSystemId(camp); } _campaignRepo.Save(camp);
something which would implement that logic on the db level if it is possible. So what is the way to do an upsert if there is one?
Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.
Introduction. In MongoDB, upsert is a method that is used to insert and update the value in any operation. In other words, the MongoDB upsert method is a combination of insert and update (insert + update = upsert). By default, the upsert method's value is always false.
Version 2 of the MongoDB C# driver requires setting the IsUpsert
flag in the write commands. This example will upsert an entire document.
var newDoc = new BsonDocument { { "_id", 123 }, { "someKey", "someValue" } }; var result = await collection.ReplaceOneAsync( filter: new BsonDocument("_id", 123), options: new ReplaceOptions { IsUpsert = true }, replacement: newDoc);
Version 1 of the MongoDB C# driver implements this logic within the Save
command.
var newDoc = new BsonDocument { { "_id", 123 }, { "someKey", "someValue" } }; collection.Save(newDoc);
The Save method is a combination of Insert and Update. If the Id member of the document has a value, then it is assumed to be an existing document and Save calls Update on the document (setting the Upsert flag just in case it actually is a new document after all). Otherwise it is assumed to be a new document and Save calls Insert after first assigning a newly generated unique value to the Id member.
Reference: http://mongodb.github.io/mongo-csharp-driver/1.11/driver/#save-tdocument-method
Note: This does require the proper mapping of the Id field however. More info on that here: http://mongodb.github.io/mongo-csharp-driver/1.11/serialization/#identifying-the-id-field-or-property
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