How to rename a Mongo collection to Mongoid?

I have a collection called artists, I would like to rename it to artist_lookups. How to do it?

+4
source share
4 answers

From 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 allow you to save your Artist model in the artist_lookups collection.

If you want to save the existing data in the artists collection and rename it, I suggest you temporarily close the application, rename the collection to artist_lookups on your MongoDB server and restart the application.

+4
source

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" ) 
+4
source

Very simple, in the mongo shell, do the following:

db.artists.renameCollection ("artist_lookups");

if you want to remove artist_lookups if it exists:

db.artists.renameCollection ("artist_lookups", true);

You can get some exception.

  • 10026 - Raised if the source namespace does not exist.
  • 10027 - Restores if the target namespace exists and dropTarget is either false or unspecified.
  • 15967 - Raised if the target namespace is an invalid collection name.
+1
source
 db.artists.renameCollection("artist_lookups") 

will work for sure.

+1
source

All Articles