Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an upsert with MongoDB 2.0?

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.

like image 250
Revious Avatar asked May 06 '15 16:05

Revious


People also ask

Does MongoDB support Upsert?

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.

How does the Upsert option work MongoDB?

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.

Is there an Upsert option in the MongoDB insert command?

insert() provides no upsert possibility.

What is MongoDB Upsert?

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.


1 Answers

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 });
like image 190
mnemosyn Avatar answered Sep 18 '22 13:09

mnemosyn