Search code examples
ruby-on-railsmongodbmongoid

How to query MongoDB directly from Ruby instead of using Mongoid?


I am writing a migration for a Rails application that uses MongoDB and Mongoid. My migration currently uses my models that use Mongoid to query and update records, but the performance is sub-par. I am essentially updating all records in a large collection and making n+20 queries. I killed the migration after taking an hour to run locally (and didn't finish). I would like to be able to run raw queries to mongo without too much effort. I'm assuming there is some way to access a mongo driver from Mongoid since Mongoid has already loaded a connection to the database. How can I access the database to run my update queries direcly?


Solution

  • If you're using Mongoid 3, it provides easy access to its MongoDB driver: Moped. Here's an example of accessing some raw data without using Models to access the data:

    db = Mongoid::Sessions.default
    
    # inserting a new document
    collection = db[:collection_name]
    collection.insert(name: 'my new document')
    
    # finding a document
    doc = collection.find(name: 'my new document').first
    
    # iterating over all documents in a collection
    collection.find.each do |document|
      puts document.inspect
    end