How do I rename a mongo collection in Mongoid?
Asked Answered
S

4

8

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

Scum answered 22/8, 2012 at 20:23 Comment(0)
D
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.

Disgorge answered 22/8, 2012 at 20:38 Comment(1)
I can't keep the model name, because of a collision with another Artist model so I took the latter approach.Scum
S
7

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"
)
Stipe answered 11/5, 2016 at 16:16 Comment(0)
B
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.
Brout answered 27/11, 2012 at 4:26 Comment(0)
D
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.

Disgorge answered 22/8, 2012 at 20:38 Comment(1)
I can't keep the model name, because of a collision with another Artist model so I took the latter approach.Scum
F
2
db.artists.renameCollection("artist_lookups")

will work for sure.

Fremd answered 4/10, 2014 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.