I have a collection called artists, i'd like to rename it to artist_lookups. How do I do this?
Asked
Active
Viewed 5,667 times
4 Answers
6
With mongoid5 / mongo ruby driver 2:
# if you need to check whether foo exists
return unless Mongoid.default_client.collections.map(&:name).include?('foo')
# rename to bar
Mongoid.default_client.use(:admin).command(
renameCollection: "#{Mongoid.default_client.database.name}.foo",
to: "#{Mongoid.default_client.database.name}.bar"
)

dB.
- 4,700
- 2
- 46
- 51
5
Very simple, in mongo shell, do that:
db.artists.renameCollection( "artist_lookups" );
if you want to drop artist_lookups if it exist:
db.artists.renameCollection( "artist_lookups", true );
Some exception you can got.
- 10026 – Raised if the source namespace does not exist.
- 10027 – Raised if the target namespace exists and dropTarget is either false or unspecified.
- 15967 – Raised if the target namespace is an invalid collection name.

Sonrobby
- 3,112
- 8
- 30
- 38
4
From the Mongoid Docs:
class Band
include Mongoid::Document
store_in collection: "artists", database: "music", session: "secondary"
end
Use store_in collection: "artist_lookups"
in your model. This will let you store your Artist
model in the artist_lookups
collection.
If you want to preserve the existing data in the artists
collection, and rename it, I suggest shutting down your app temporarily, renaming the collection to artist_lookups
on your MongoDB server, and then restarting the app.

Vickash
- 1,076
- 8
- 8
-
I can't keep the model name, because of a collision with another Artist model so I took the latter approach. – Billy Aug 22 '12 at 21:42
2
db.artists.renameCollection("artist_lookups")
will work for sure.

Pang
- 9,564
- 146
- 81
- 122

Kajal Rangwani
- 29
- 2