The interface of MongoDB has completely changed from the previous one. Here you can see the official documentation with some examples about how to search, insert and update but what about upserts?
Idea for meta: I've tried to search on google and on SO but many resources refer to the old interface. Maybe it would be nice to create a MongoLegacy tag.
Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter. In that case, the applied update operation will update the documents. If the value is true and no documents match the condition, this option inserts a new document into the collection.
Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents.
insert() provides no upsert possibility.
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.
Pass an instance of UpdateOptions
as the options parameter in UpdateOneAsync(filter, update, options)
, e.g.:
collection.UpdateOneAsync(p => p.Id == user.Id,
Builders<User>.Update.Set(p => p.Name, "John"),
new UpdateOptions { IsUpsert = true });
EDIT
To replace the document, call ReplaceOneAsync
instead:
collection.ReplaceOneAsync(p => p.Id == user.Id,
user,
new ReplaceOptions { IsUpsert = true });
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