Mongoid criteria
The Mongoid::Criteria
module is the core object for querying MongoDB. This includes the entire Origin DSL for querying along with other goodies. Every time a query is fired, a criterion is created. For example, in the following query, we do not get back a result but a criterion object:
irb> Book.exists(awards: true) => #<Mongoid::Criteria selector: {"awards"=>{"$exists"=>true}} options: {} class: Book embedded: false>
This criterion can now be chained with other criteria, just like ActiveRelation
. This helps us fire a single query to the database only when all the criteria are fully resolved:
> Book.exists(awards: true).count => 20
In addition to the methods provided in Origin, some helpful criteria are mentioned as follows:
|
Author.count Author.where(name: 'Charles').length Author.where(name: 'Charles').size |
This finds the number of documents in the collection. |
|
Author.distinct(:name) Author... |