Search code examples
rubymongodbmongoid

How to execute runCommand with Mongoid > v7?


How to run db.runCommand in newer versions of mongoid.

Example: MyModel.collection.database.command(eval: "db.runCommand ( { compact: 'sessions' } )" )

used to work in older version of mongoid but it now throws "DcSite.collection.database.command(eval: "db.runCommand ( { compact: 'sessions' } )" )" error.

by TheR


Solution

  • You can just use the command method directly. For example:

    class Band
      include Mongoid::Document
    end
    Band.create!
    Band.collection.database.command(compact: "bands")
    

    The command method executes a runCommand under the hood, and parses the given hash to send to the database.

    Here are the docs on the command method: https://www.mongodb.com/docs/ruby-driver/master/api/Mongo/Database.html#command-instance_method