MongoDB とドライバー
定義
db.collection.renameCollection(target, dropTarget)コレクションの名前を変更します。
renameCollectionデータベースコマンドのラッパーを提供します。
パラメーター
Parameter | タイプ | 説明 |
|---|---|---|
| string | コレクションの新しい名前。文字列を引用符で囲みます。詳細は、「命名制限」を参照してください。 |
| ブール値 | 任意。 |
互換性
このメソッドは、次の環境でホストされている配置で使用できます。
- 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 のバージョン
Stable API でのサポート
MongoDB 8.1 以降、Stable API V1 に renameCollection が含まれています。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 でのロックの詳細については、「FAQ: 同時実行性」を参照してください。
レプリカセットでのリソース ロック
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 )が既存のコレクションの名前である場合、操作は失敗します。