Queries¶
On this page
One of MongoDB’s greatest features is its ability to execute dynamic queries, provided through a familiar Arel-style DSL.
Queries¶
All queries in Mongoid are Mongoid::Criteria
, which is a chainable and
lazily evaluated wrapper to a MongoDB dynamic query. Criteria only
touch the database when they need to, for example on iteration of the
results, and when executed wrap a cursor in order to keep memory
management and performance predictable.
Queryable DSL¶
Query methods are available off a Mongoid::Criteria
object
as well as off the model’s class.
With each chained method on a criteria, a newly cloned criteria is returned with the new query added. This is so that with scoping or exposures, for example, the original queries are unmodified and remain reusable.
Query Cache¶
If Mongoid’s QueryCache is enabled, it will cache queries and avoid sending requests to the database for identical queries.
To enable the QueryCache:
Additional Query Methods¶
Mongoid also has some helpful methods on criteria.
Operation | Example |
---|---|
Get a count of persisted documents. Note this will always hit the database for the count. |
|
Get a list of distinct values for a single field. Note this will always hit the database for the distinct values. |
|
Iterate over all matching documents in the criteria. |
|
Determine if any matching documents exist. Will return true if there are 1 or more. |
|
Find a document or multiple documents by their ids. Will raise an error by default if any of the ids do not match. |
|
Find a document by the provided attributes, and if not found raise an error or return nil depending on the * ``raise_not_found_error`` *configuration option. |
|
Find a document by the provided attributes, and if not found create and return a newly persisted one. |
|
Find a document by the provided attributes, and if not found return a new one. |
|
Finds a single document given the provided criteria. This automatically adds a sort on id. Opt out of adding the id sort with the {id_sort: :none} option. |
|
Find the first document by the provided attributes, and if not found create and return a newly persisted one. |
|
Find the first document by the provided attributes, and if not found
create and return a newly persisted one using |
|
Find the first document by the provided attributes, and if not found return a new one. |
|
Find documents for a provided javascript expression. This will wrap the javascript in a `BSON::Code` object which is the safe way to avoid javascript injection attacks.* |
|
Same as count but caches subsequent calls to the database |
|
Get all the values for the provided field. Returns nil for unset fields and for non-existent fields. |
Eager Loading¶
Mongoid provides a facility to eager load documents
from relations to prevent the n+1 issue when
iterating over documents with relation access. Eager loaded is supported on
all relations with the exception of polymorphic belongs_to
associations.
Queries + Persistence¶
Mongoid supports persistence operations off of criteria in a light capacity for when you want to expressively perform multi document inserts, updates, and deletion.
Operation | Example |
---|---|
Create a newly persisted document. |
|
Create a newly persisted document and raise an exception on validation failure. |
|
Create a new (unsaved) document. |
|
Update attributes of the first matching document. |
|
Update attributes of all matching documents. |
|
Perform an $addToSet on all matching documents. |
|
Perform a $bit on all matching documents. |
|
Perform an $inc on all matching documents. |
|
Perform a $pop on all matching documents. |
|
Perform a $pull on all matching documents. |
|
Perform a $pullAll on all matching documents. |
|
Perform a $push on all matching documents. |
|
Perform a $pushAll on all matching documents. |
|
Perform a $rename on all matching documents. |
|
Perform a $set on all matching documents. |
|
Perform a $unset on all matching documents. |
|
Deletes all matching documents in the database. |
|
Deletes all matching documents in the database while running callbacks for all. This loads all documents into memory and can be an expensive operation. |
Scoping¶
Scopes provide a convenient way to reuse common criteria with more business domain style syntax.
Named Scopes¶
Named scopes are simply criteria defined at class load that are referenced by a provided name. Just like normal criteria, they are lazy and chainable.
Named scopes can take procs and blocks for accepting parameters or extending functionality.
Default Scopes¶
Default scopes can be useful when you find yourself applying the same criteria to most queries, and want something to be there by default. Default scopes take procs that return criteria objects.
You can tell Mongoid not to apply the default scope by using
unscoped
, which can be inline or take a block.
You can also tell Mongoid to explicitly apply the default scope again later to always ensure it’s there.
If you are using a default scope on a model that is part of a relation, you must reload the relation to have scoping reapplied. This is important to note if you change a value of a document in the relation that would affect its visibility within the scoped relation.
Class Methods¶
Class methods on models that return criteria objects are also treated like scopes, and can be chained as well.
Map/Reduce¶
Mongoid provides a DSL around MongoDB’s map/reduce framework, for performing custom map/reduce jobs or simple aggregations.
Execution¶
You can tell Mongoid off the class or a criteria to perform a map/reduce
by calling map_reduce
and providing map and reduce javascript
functions.
Just like criteria, map/reduce calls are lazily evaluated. So nothing will hit the database until you iterate over the results, or make a call on the wrapper that would need to force a database hit.
The only required thing you provide along with a map/reduce is where to
output the results. If you do not provide this an error will be raised.
Valid options to #out
are:
inline: 1
: Don’t store the output in a collection.replace: "name"
: Store in a collection with the provided name, and overwrite any documents that exist in it.merge: "name"
: Store in a collection with the provided name, and merge the results with the existing documents.reduce: "name"
: Store in a collection with the provided name, and reduce all existing results in that collection.