- Working With Data >
- CRUD Operations
CRUD Operations¶
On this page
Saving Documents¶
Mongoid supports all expected CRUD operations for those familiar with other Ruby mappers like Active Record or Data Mapper. What distinguishes Mongoid from other mappers for MongoDB is that the general persistence operations perform atomic updates on only the fields that have changed instead of writing the entire document to the database each time.
The persistence sections will provide examples on what database operation is performed when executing the documented command.
Standard¶
Mongoid’s standard persistence methods come in the form of common methods you would find in other mapping frameworks. The following table shows all standard operations with examples.
Operation | Example |
---|---|
Insert a document or multiple documents into the database, raising an error if a validation or server error occurs. Pass a hash of attributes to create one document with the specified attributes, or an array of hashes to create multiple documents. If a single hash is passed, the corresponding document is returned. If an array of hashes is passed, an array of documents corresponding to the hashes is returned. If a block is given to If there is a problem saving any of the documents, such as a validation error or a server error, an exception is raised and, consequently, none of the documents are returned. However, if an array of hashes was passed and previous documents were successfully saved, those documents will remain in the database. |
|
Instantiate a document or multiple documents and, if validations pass, insert them into the database.
If any validation errors are encountered, the respective document
is not inserted but is returned along with documents that were inserted.
Use |
|
Save the changed attributes to the database atomically, or insert the document if new. Raises an exception if validations fail or there is a server error. Returns true if the changed attributes were saved, raises an exception otherwise. |
|
Save the changed attributes to the database atomically, or insert the document if new. Returns true if the changed attributes were saved. Returns false if there were any validation errors. Raises an exception if the document passed validation but there was a server error during the save. Pass |
|
Update the document attributes in the database. Will return true if validation passed, false if not. |
|
Update the document attributes in the database and raise an error if validation failed. |
|
Update a single attribute, bypassing validations. |
|
Performs a MongoDB replace with upsert on the document. If the document
exists in the database, it will get overwritten with the current
document in the application (any attributes present in the database but
not in the application’s document instance will be lost).
If the document does not exist in the database, it will be inserted.
Note that this only runs the |
|
Update the document’s updated_at timestamp, optionally with one extra
provided time field. This will cascade the touch to all
Attempting to touch a destroyed document will raise |
|
Deletes the document from the database without running callbacks. If the document is not persisted, Mongoid will attempt to delete from
the database any document with the same |
|
Deletes the document from the database while running destroy callbacks. If the document is not persisted, Mongoid will attempt to delete from
the database any document with the same |
|
Deletes all documents from the database without running any callbacks. |
|
Deletes all documents from the database while running callbacks. This is a potentially expensive operation since all documents will be loaded into memory. |
Mongoid provides the following persistence-related attributes:
Attribute | Example |
---|---|
Returns |
|
Returns |
Atomic¶
Although Mongoid performs atomic operations under the covers by default, there may be cases where you want to do this explicitly without persisting other fields. Mongoid provides support for all of these operations as well. When executing atomic operations via these methods, callbacks and validations are not invoked.
Operation | Example |
---|---|
Performs an atomic $addToSet on the field. |
|
Performs an atomic $bit on the field. |
|
Performs an atomic $inc on the field. |
|
Performs an atomic $pop on the field. |
|
Performs an atomic $pull on the field. |
|
Performs an atomic $pullAll on the field. |
|
Performs an atomic $push on the field. |
|
Performs an atomic $rename on the field. |
|
Updates an attribute on the model instance and, if the instance is already persisted, performs an atomic $set on the field, bypassing validations.
|
|
Performs an atomic $unset on the field. |
Atomic Operation Grouping¶
Atomic operations may be grouped together using the #atomically
method
on a document. All operations inside the block given to #atomically
are sent to the cluster in a single atomic command. For example:
#atomically
blocks may be nested. The default behavior is to write
changes performed by each block as soon as the block ends:
This behavior can be changed by specifying the join_context: true
option
to #atomically
, or globally by setting the join_contexts
configuration option to true
. When
context joining is enabled, nested #atomically
blocks are joined with
the outer blocks, and only the outermost block (or the first block where
join_contexts
is false) actually writes changes to the cluster.
For example:
The context joining behavior can be enabled globally by default by setting
join_context
option in Mongoid configuration. In this case specifying
join_context: false
on an #atomically
block can be used to
obtain the independent persistence context behavior.
If an exception is raised in an #atomically
block which has not yet
persisted its changes to the cluster, any pending attribute changes on
Mongoid models are reverted. For example:
Atomic operations described in this section apply to one document at a time,
therefore nesting #atomically
blocks invoked on multiple documents does
not make changes to the different documents be persisted atomically together.
However, MongoDB offers multi-document transactions
as of server version 4.0 which provide atomic persistence across multiple
documents.
Reloading¶
Use the reload
method to fetch the most recent version of a document from
the database. Any unsaved modifications to the document’s attributes are lost:
When a document is reloaded, all of its embedded associations are also reloaded in the same query (since embedded documents are stored in the parent document on the server). If a document has referenced associations, the loaded associations’ are not reloaded but their values are cleared, such that these associations would be loaded from the database at the next access.
Note
Some operations on associations, for example assignment, persists the new document. In these cases there may not be any unsaved modifications to revert by reloading. In the following example, the assignment of the empty array to the association is immediately persisted and reloading does not make any changes to the document:
If the model has a shard key defined, the shard key value is included in the reloading query.
If the database does not contain a matching document, Mongoid normally raises
Mongoid::Errors::DocumentNotFound
. However, if the configuration option
raise_not_found_error
is set to false
, and the database does not
contain a matching document, Mongoid replaces the current document with a newly
created document whose attributes are set to default values. Importantly, this
generally causes the _id
of the document to change, as the following
example demonstrates:
For this reason, it is not recommended to use reload
when
raise_not_found_error
is set to false
.
Reloading Unsaved Documents¶
reload
can be called when the document has not yet been persisted.
In this case reload
performs a find
query using the id
value
specified in the document (and the shard key value, if a shard key is defined):
Accessing Field Values¶
Mongoid provides several ways of accessing field values.
Note
All of the access methods described below raise
ActiveModel::MissingAttributeError
when the field being accessed is
projected out, either by virtue of not being included in
only or by virtue of being included in
without. This applies to both reads and writes.
Getters & Setters¶
The recommended way is to use the getter and setter methods generated for each declared field:
To use this mechanism, each field must be explicitly declared, or the model class must enable dynamic fields.
Custom Getters & Setters¶
It is possible to explicitly define the getter and setter methods to provide
custom behavior when reading or writing fields, for example value
transformations or storing values under different field names. In this case
read_attribute
and write_attribute
methods can be used to read and
write the values directly into the attributes hash:
read_attribute
& write_attribute
¶
The read_attribute
and write_attribute
methods can be used explicitly
as well. Note that if a field specifies its storage field name, both read_attribute
and write_attribute
accept either the declared field name or the storage field name for operations:
read_attribute
and write_attribute
do not require that a field with
the used name is defined, but writing field values with write_attribute
does not cause the respective field to be defined either:
When read_attribute
is used to access a missing field, it returns nil
.
Hash Access¶
Mongoid model instances define the []
and []=
methods to provide
Hash
style access to the attributes. []
is an alias for
read_attribute
and []=
is an alias for write_attribute
; see
the section on read_attribute and write_attribute
for the detailed description of their behavior.
Bulk Attribute Writes¶
In cases where you want to set multiple field values at once, there are a few different ways of accomplishing this as well.
Dirty Tracking¶
Mongoid supports tracking of changed or “dirty” fields with an API that mirrors that of Active Model. If a defined field has been modified in a model the model will be marked as dirty and some additional behavior comes into play.
Viewing Changes¶
There are various ways to view what has been altered on a model. Changes are recorded from the time a document is instantiated, either as a new document or via loading from the database up to the time it is saved. Any persistence operation clears the changes.
Note
Setting the associations on a document does not cause the changes
or
changed_attributes
hashes to be modified. This is true for all associations
whether referenced or embedded. Note that changing the _id(s) field on
referenced associations does cause the changes to show up in the changes
and the changed_attributes
hashes.
Resetting Changes¶
You can reset changes of a field to its previous value by calling the reset method.
Persistence¶
Mongoid uses dirty tracking as the core of its persistence operations. It looks at the
changes on a document and atomically updates only what has changed, unlike other frameworks
that write the entire document on each save. If no changes have been made, Mongoid will
not hit the database on a call to Model#save
.
Viewing Previous Changes¶
After a document has been persisted, you can see what the changes were previously by
calling Model#previous_changes
.
Updating Container Fields¶
Be aware that, until MONGOID-2951 is resolved, all fields including container ones must be assigned to for their values to be persisted to the database.
For example, adding to a set like this does not work:
Instead, the field value must be modified outside of the model and assigned back to the model as follows: