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?
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.
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.
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.
insert() provides no upsert possibility.
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/
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
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