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')
@xixilive
Copy link

great!!

@khoan
Copy link

khoan commented Apr 22, 2013

% Mongoid::VERSION
=> "4.0.0"
% Mongoid.database
=> NoMethodError: undefined method `database' for Mongoid:Module

@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