Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rename a mongo collection in Mongoid?

I have a collection called artists, i'd like to rename it to artist_lookups. How do I do this?

like image 558
Billy Avatar asked Aug 22 '12 20:08

Billy


People also ask

How do I rename a MongoDB collection?

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.

How do I rename a Sharded 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.

How do you rename a collection in MongoDB using Python?

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.


3 Answers

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"
)
like image 188
dB. Avatar answered Oct 05 '22 21:10

dB.


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.

like image 45
Vickash Avatar answered Oct 05 '22 20:10

Vickash


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.
like image 26
Sonrobby Avatar answered Oct 05 '22 21:10

Sonrobby