2

I am working within a Rails app that uses MongoDB and Mongoid. I can run mongo queries using the mongo shell environment, but I'd love to play with Mongoid in irb. Is that something that I can do? If so, could someone please tell me how?

Thanks :)

Rebekah Waterbury
  • 22,236
  • 5
  • 23
  • 28

3 Answers3

6

As mentioned by Semyon the easiest option is to use:

$ rails console

If you want to do it manually, run up irb and prepend it with the environment you want (which is most likely development).

e.g./

$ RACK_ENV=development irb

Then require the mongoid gem & load your mongoid config & you should be able to use Mongoid. You'll also need to require any models you wish to use.

e.g/

> require 'mongoid'

> Mongoid.load!("path/to/your/mongoid.yml")

BTW. I'd recommend using pry rather than irb, it's like irb but you can find things out without leaving your terminal amongst other things.

e.g./

running

> ls Mongoid

shows me all the possible constants, Class & Instance Methods for Mongoid

constants: Atomic  Attributes  Callbacks  Collection  Collections  Components  Config  Contexts  Copyable  Criteria  Criterion  Cursor  DefaultScope  Dirty  Document  Errors  Extensions  Extras  Factory  Fields  Finders  Hierarchy  Identity  IdentityMap  Indexes  Inspection  Javascript  JSON  Keys  Logger  Matchers  MONGODB_VERSION  MultiDatabase  MultiParameterAttributes  NamedScope  NestedAttributes  Observer  Paranoia  Persistence  Relations  Reloading  Safety  Scope  Serialization  Sharding  State  Threaded  Timestamps  Validations  VERSION  Versioning
Mongoid#methods: add_language  add_observer  allow_dynamic_fields  allow_dynamic_fields=  allow_dynamic_fields?  autocreate_indexes  autocreate_indexes=  autocreate_indexes?  blacklisted_options  config  configure  count_observers  database  database=  databases  databases=  default_logger  destructive_fields  from_hash  identity_map_enabled  identity_map_enabled=  identity_map_enabled?  include_root_in_json  include_root_in_json=  include_root_in_json?  include_type_for_serialization  include_type_for_serialization=  include_type_for_serialization?  instantiate_observers  load!  logger  logger=  master  master=  max_retries_on_connection_failure  max_retries_on_connection_failure=  max_retries_on_connection_failure?  notify_observers  observer_instances  observers  observers=  parameterize_keys  parameterize_keys=  parameterize_keys?  persist_in_safe_mode  persist_in_safe_mode=  persist_in_safe_mode?  preload_models  preload_models=  preload_models?  purge!  raise_not_found_error  raise_not_found_error=  raise_not_found_error?  reconnect!  scope_overwrite_exception  scope_overwrite_exception=  scope_overwrite_exception?  skip_version_check  skip_version_check=  skip_version_check?  time_zone  time_zone=  time_zone?  unit_of_work  use_activesupport_time_zone  use_activesupport_time_zone=  use_activesupport_time_zone?  use_utc  use_utc=  use_utc?
Mongoid#methods: add_language  add_observer  allow_dynamic_fields  allow_dynamic_fields=  allow_dynamic_fields?  autocreate_indexes  autocreate_indexes=  autocreate_indexes?  blacklisted_options  config  configure  count_observers  database  database=  databases  databases=  default_logger  destructive_fields  from_hash  identity_map_enabled  identity_map_enabled=  identity_map_enabled?  include_root_in_json  include_root_in_json=  include_root_in_json?  include_type_for_serialization  include_type_for_serialization=  include_type_for_serialization?  instantiate_observers  load!  logger  logger=  master  master=  max_retries_on_connection_failure  max_retries_on_connection_failure=  max_retries_on_connection_failure?  notify_observers  observer_instances  observers  observers=  parameterize_keys  parameterize_keys=  parameterize_keys?  persist_in_safe_mode  persist_in_safe_mode=  persist_in_safe_mode?  preload_models  preload_models=  preload_models?  purge!  raise_not_found_error  raise_not_found_error=  raise_not_found_error?  reconnect!  scope_overwrite_exception  scope_overwrite_exception=  scope_overwrite_exception?  skip_version_check  skip_version_check=  skip_version_check?  time_zone  time_zone=  time_zone?  unit_of_work  use_activesupport_time_zone  use_activesupport_time_zone=  use_activesupport_time_zone?  use_utc  use_utc=  use_utc?
gef
  • 7,025
  • 4
  • 41
  • 48
  • Thank you so much. I'm going to lunch now, but I'll try this when I get back :) – Rebekah Waterbury Jul 04 '12 at 20:54
  • I tried this and there was an error after the Mongoid.Load!('config/mongoid.yml') command. I put the description of this error in my original question as the comment text area was too restrictive. Could you please read the error and see if you understand what I need to do to get it working? Thanks a bunch. -R – Rebekah Waterbury Jul 04 '12 at 22:57
  • Ah yes, you need to tell it what environment you're going to use. I've modified the answer to include RACK_ENV=development :) – gef Jul 04 '12 at 23:53
  • So everything looks good initially, right database and no errors... but my Mongoid queries still don't seem to be working. I was using the count query method like this, the text between the astrisks is the error: User.count ***** NameError: uninitialized constant User ***** any thoughts? – Rebekah Waterbury Jul 05 '12 at 00:50
  • 1
    This is because the irb is executed outside of rails context. You will need to require models manually. I use this sometimes, but not for irb – Simon Perepelitsa Jul 05 '12 at 08:45
  • Could I do the same sort of thing within the rails console? When I type in require "mongoid' within the console it returns false. – Rebekah Waterbury Jul 05 '12 at 17:02
  • When a require returns false it means it's already loaded. Using rails console loads up all the files, meaning you won't have to do it manually, and it uses development mode by default. – gef Jul 05 '12 at 23:47
3

You can also start a preconfigured Rails console in your project:

$ rails console
>> MyDocument.where(:foo => 'bar').to_a
=> [...]
Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74
  • +1 - add you may use Pry with rails console - https://github.com/pry/pry/wiki/Setting-up-Rails-or-Heroku-to-use-Pry :) – gef Jul 04 '12 at 21:10
  • So this is not like the queries in the Mongoid docs. The '.to_a' addition to the query makes it work. Can you explain to me what the pattern is for updating the queries that make the native mongoid queries work in the rails console context? – Rebekah Waterbury Jul 04 '12 at 22:19
  • What do you mean? There is nothing special here. The to_a method just fetches all documents. By default queries are chainable and are not performed till the last moment – Simon Perepelitsa Jul 05 '12 at 08:43
  • I'm sorry, I am new to this, please forgive my ignorance. What I mean is: How can I use the Mongoid queries as described in the Mongoid docs? Do they always need to be manipulated in some way in order to work? If so; Can you describe specifically the patterns for how (even if it seems ridiculously basic to you)? Thanks :) – Rebekah Waterbury Jul 06 '12 at 20:36
  • 2
    They do work as they should. Are you confused only by `to_a` method? It is a common Ruby method for converting an object to an array. You can usually iterate over it without calling to_a explicitly. For example, ranges work that way. If you call 1..9 in irb you won't see an array. But you can do`(1..9).each{ |n| print n }`. The same thing applies to Mongoid Criteria (this is the kind of object returned by Document.where). You won't see an array of documents right away, but can iterate over it or convert it to an array explicitly. – Simon Perepelitsa Jul 07 '12 at 00:52
2

In Rails console

db = Mongoid::Clients.default

collection = db[:collection_name]

Now we can perform queries on the collection.

To see all possible methods use

collection.methods.sort!
Eiko
  • 25,601
  • 15
  • 56
  • 71
Venu
  • 201
  • 2
  • 4