Skip to content

Instantly share code, notes, and snippets.

@dira
Created March 28, 2012 10:14
Show Gist options
  • Save dira/2225205 to your computer and use it in GitHub Desktop.
Save dira/2225205 to your computer and use it in GitHub Desktop.
Rename a Mongoid collection
# want to nest `Video` under `Media`; had a `videos` collection
# rename the collection:
Mongoid.database.drop_collection('videos')
Mongoid.database.rename_collection('videos', 'media')
# or
Mongoid.database.collection('videos').rename('media')
# change the type of all the existing records
Media.update_all(_type: 'Video')
@seifsallam
Copy link

Same problem here as @khoan. Any ideas?

Mongoid.database
# => NoMethodError: undefined method `database' for Mongoid:Module

@dcarneiro
Copy link

This worked for me:

% Mongoid::VERSION
=> "4.0.2"
% Mongoid::Sessions.default[:videos].rename(:media)
=> {"ok"=>1.0}

@Unnumbered
Copy link

You can use following code for 5.x:

client = Mongoid.default_client
current_db = client.database
admin_db = Mongo::Database.new(client, Mongo::Database::ADMIN, current_db.options)
admin_db.command(renameCollection: "#{current_db.name}.old_name", to: "#{current_db.name}.new_name")

https://gist.github.com/Unnumbered/2feac77bba9fd87a9b417021e6deb76e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment