I have a collection called artists, i'd like to rename it to artist_lookups. How do I do this?
renameCollection() method is used to rename a collection. The new name of the collection. Enclose the string in quotes. If true, mongod drops the target of renameCollection prior to renaming the collection.
Sharded Collections Starting in MongoDB 5.0, you can use the renameCollection command to change the name of a sharded collection. The target database must be the same as the source database.
The PyMongo function rename() is used to rename a collection. The rename operation fails if the new name is not an instance of basestring or it is an invalid collection name. Parameters : new_name : The new name of the collection.
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"
)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With