Search code examples
rubymongodbmongoidupsert

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?


Solution

  • 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/