如何在 Mongoid 中重命名 mongo 集合?

Bil*_*lly 6 mongoid mongoid3

我有一个名为艺术家的收藏,我想将其重命名为artist_lookups。我该怎么做呢?

dB.*_*dB. 6

使用 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)


Son*_*bby 5

非常简单,在 mongo shell 中执行以下操作:

\n\n
\n

db.artists.renameCollection( "artist_lookups" );

\n
\n\n

如果你想删除 Artist_lookups(如果存在):

\n\n
\n

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

\n
\n\n

你可以得到一些例外。

\n\n
    \n
  • 10026 \xe2\x80\x93 如果源命名空间不存在,则引发该错误。
  • \n
  • 10027 \xe2\x80\x93 如果目标命名空间存在并且 dropTarget 为 false 或未指定,则引发该错误。
  • \n
  • 15967 \xe2\x80\x93 如果目标命名空间是无效的集合名称,则引发该错误。
  • \n
\n


Vic*_*ash 4

来自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 服务器上的集合,然后重新启动应用程序。