MongoMapper provides support for Dynamic Querying in its finders, familiar to many Rails developers. Similar to dynamic finders in ActiveRecord , MongoMapper provides a finder for every key defined in your document.
Let’s start with a simple User model:
Let’s create some users that we can query dynamically later:
We can now dynamically query for a user by one or multiple keys like so:
In order to query for all possible users simply add the all keyword to the query which will return an array of results
Remember the scopes that we defined in our User class earlier? Well MongoMapper allows you to dynamically query those scopes too:
Another convenient feature that MongoMapper provides (similar to ActiveRecord) is the ability to find or initialize a record by one or more keys:
In the above queries, if a user is not found, the user is then initialized with the attributes given to the dynamic query. If you want to save and actually create those records using dynamic finders, you can write the above queries like so:
Dynamic Querying also has support for the ! operator. So if a document is not found in a dynamic query using the ! operator, an exception will be raised likewise: