对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

db. 集合.renameCollection()(mongosh方法)

带驱动程序的 MongoDB

本页面文档 mongosh 方法。要查看 MongoDB 驱动程序中的等效方法,请参阅您的编程语言的相应页面:
db.collection.renameCollection(target, dropTarget)

重命名集合。为 renameCollection 数据库命令提供包装器。

Parameter
类型
说明

target

字符串

集合的新名称。将字符串括在引号中。请参阅命名限制。

dropTarget

布尔

可选。如果 true,mongod 在重命名集合之前删除 renameCollection 中的 target。默认值为 false。

此方法可用于以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

注意

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.

从 MongoDB 8.1 开始,renameCollection 包含在 Stable API V1 中。要在 Stable API 中使用 renameCollection,您必须将驱动程序连接到运行 MongoDB 8.1 或更高版本的部署。

db.collection.renameCollection() 方法通过更改与给定集合相关的元数据,在集合内进行操作。

有关其他警告和消息,请参阅文档 renameCollection。

警告

The db.collection.renameCollection() method and renameCollection command invalidate open cursors. This creates an invalidate event for any existing change streams opened on the source or target collection, and also interrupts queries that are currently returning data from the renamed collection.

  • 该方法具有以下限制:

    • db.collection.renameCollection() 无法在各数据库之间移动数据集。将 renameCollection 用于此类重命名操作。

    • 您无法重命名视图。

    • 您无法将集合重命名为其自身。如果您尝试将集合重命名为其自身,则会引发 IllegalOperation 错误。

注意

从 MongoDB 9.0 开始,您可以对时间序列集合使用 db.collection.renameCollection()。

如果源集合上正在进行索引构建,重命名操作将失败并显示 BackgroundOperationInProgressForNamespace 错误。如果目标集合上正在进行索引构建,并且您指定 dropTarget: true,则操作也会失败。

要重命名集合,请等待索引构建完成,然后重试该操作。要检查是否有正在进行的索引构建,请使用 db.currentOp() 方法。

在版本5.0中进行了更改。

重命名分片集群中的分片集合或非分片集合时,源集合和目标集合都以独占方式锁定在每个分片上。对源集合和目标集合的后续操作必须等待重命名操作完成。

有关 MongoDB 中锁定的更多信息,请参阅常见问题解答:并发。

renameCollection() obtains an exclusive lock on the source and target collections for the duration of the operation. All subsequent operations on the collections must wait until renameCollection() completes.

A mongodump started with --oplog fails if a client issues db.collection.renameCollection() during the dump process. See mongodump.--oplog for more information.

在集合对象上调用 db.collection.renameCollection() 方法。例如:

db.rrecord.renameCollection("record")

该操作会将 rrecord 集合重命名为 record。如果目标名称(即 record)是现有集合的名称,则该操作会失败。

给本页内容打分