Moped: Rename mongodb collection

830 Views Asked by At

How can one rename a collection, using Mongoid + Moped driver?

Is there a Moped implementation of http://docs.mongodb.org/manual/reference/command/renameCollection/?

3

There are 3 best solutions below

2
On

Renaming a collection is a serious change and won't work in a sharded environment.

But, you could do that via an app using (probably) the admin db and db commands. So I probably would take a look into: the Moped Driver Docs

0
On

I just recently migrated to Mongoid 7.x and sessions no longer exist (it's now clients)

The API seems to have removed .rename() so instead you can use this:

client = Mongo::Database.new(Mongoid.default_client, Mongo::Database::ADMIN, Mongoid.default_client.database.options)
client.command(renameCollection: "#{source_db}.#{source_collection}", 
    to: "#{target_db}.#{target_collection}", dropTarget: true)
0
On

A collection can be renamed via the Moped::Collection#rename method.

Here's an example, renaming the "foo" collection to "bar":

Mongoid::default_session[:foo].rename("bar")

Under the hood, the command is constructed like so:

session.
  with(database: "admin", read: :primary).
  command(renameCollection: "#{database.name}.#{name}", to: "#{database.name}.#{to_name}")