带驱动程序的 MongoDB
定义
db.collection.renameCollection(target, dropTarget)重命名集合。为
renameCollection数据库命令提供包装器。
参数
Parameter | 类型 | 说明 |
|---|---|---|
| 字符串 | 集合的新名称。将字符串括在引号中。请参阅命名限制。 |
| 布尔 | 可选。如果 |
兼容性
此方法可用于以下环境中托管的部署:
- 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 Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
稳定的 API 支持
从 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.
互动 mongodump
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)是现有集合的名称,则该操作会失败。