In MongoDB, you can use the db.runCommand()
method to rename a collection. The db.runCommand()
method takes a document as its argument, and the document must contain the following props:
renameCollection
: The name of the collection to be renamed.to
: The new name of the collection.
For example, to rename the collection your_database.your_table
to your_database.your_new_table_name
, you would use the following command:
db.runCommand({renameCollection: "your_database.your_table", to: "your_database.your_new_table_name"});
If the rename operation was successful, the db.runCommand()
method will return a document with the status of the operation.
{
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1689910863, i: 27 }),
signature: {
hash: Binary(Buffer.from("3f999f9155064aa974469f94304958eba5eef4b3", "hex"), 0),
keyId: Long("7200478234696220854")
}
},
operationTime: Timestamp({ t: 1689910863, i: 27 })
}
Here are some additional things to keep in mind when renaming a collection:
- You can only rename a collection that exists in the current database.
- You cannot rename a collection to a name that already exists in the database.
- If you rename a collection that is being used by a running application, the application may need to be restarted in order to see the changes.