Module: Mongoid::Persistable::Upsertable
- Included in:
- Mongoid::Persistable
- Defined in:
- lib/mongoid/persistable/upsertable.rb
Overview
Defines behavior for persistence operations that upsert documents.
Instance Method Summary collapse
-
#upsert(options = {}) ⇒ true
Perform an upsert of the document.
Instance Method Details
#upsert(options = {}) ⇒ true
Perform an upsert of the document. If the document does not exist in the database, then Mongo will insert a new one, otherwise the fields will get overwritten with new values on the existing document.
If the replace option is true, unspecified attributes will be dropped, and if it is false, unspecified attributes will be maintained. The replace option defaults to false in Mongoid 9.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/mongoid/persistable/upsertable.rb', line 36 def upsert( = {}) prepare_upsert() do if [:replace] if [:set_on_insert] raise ArgumentError, "cannot specify :set_on_insert with `replace: true`" end collection.find(atomic_selector).replace_one( as_attributes, upsert: true, session: _session) else attrs = { "$set" => as_attributes } attrs["$setOnInsert"] = [:set_on_insert] if [:set_on_insert] collection.find(atomic_selector).update_one( attrs, upsert: true, session: _session) end end end |