使用 mongoid5 / mongo ruby 驱动程序 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"
)
Run Code Online (Sandbox Code Playgroud)
非常简单,在 mongo shell 中执行以下操作:
\n\n\n\n\ndb.artists.renameCollection( "artist_lookups" );
\n
如果你想删除 Artist_lookups(如果存在):
\n\n\n\n\ndb.artists.renameCollection( "artist_lookups", true );
\n
你可以得到一些例外。
\n\n来自Mongoid 文档:
class Band
include Mongoid::Document
store_in collection: "artists", database: "music", session: "secondary"
end
Run Code Online (Sandbox Code Playgroud)
store_in collection: "artist_lookups"在您的模型中使用。这将允许您将Artist模型存储在artist_lookups集合中。
如果您想保留artists集合中的现有数据并重命名它,我建议暂时关闭您的应用程序,将集合重命名为artist_lookupsMongoDB 服务器上的集合,然后重新启动应用程序。