Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upsert in Mongoid

Is there a built-in way to make upsert (insert if not exists) in Mongoid? Or should I check if an item exists first and only after that make insert/update?

like image 887
Alexandre Avatar asked Nov 11 '12 02:11

Alexandre


People also ask

What is Upsert in mongoose?

May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.

What is the use of Upsert?

The term upsert is a portmanteau – a combination of the words “update” and “insert.” In the context of relational databases, an upsert is a database operation that will update an existing row if a specified value already exists in a table, and insert a new row if the specified value doesn't already exist.

What Upsert does in MongoDB?

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.

Is there an Upsert option in the MongoDB insert command?

insert() provides no upsert possibility.


2 Answers

There is a built-in upsert method in Mongoid already

Performs a MongoDB upsert on the document. If the document exists in the database, it will get overwritten with the current attributes of the document in memory. If the document does not exist in the database, it will be inserted. Note that this only runs the {before|after|around}_upsert callbacks.

Taken from https://www.mongodb.com/docs/mongoid/7.3/tutorials/mongoid-persistence/

like image 159
gef Avatar answered Nov 15 '22 03:11

gef


Here is an example

person = Person.new(
   first_name: "Heinrich",
   last_name: "Heine"
)
person.upsert

Source: https://mongoid.github.io/old/en/mongoid/docs/persistence.html

like image 33
Vitalii Isaev Avatar answered Nov 15 '22 03:11

Vitalii Isaev