MongoDB Rename Collection
Names change as applications evolve: usr becomes users, or orders needs to move into an archive database. MongoDB can rename a collection in place, keeping all of its documents, indexes and options, without copying the data.
This tutorial shows how to rename a collection with renameCollection(), how to move a collection to another database, how to replace an existing collection, and which restrictions and side effects to plan for.
1. The renameCollection() Method
db.<collection>.renameCollection(<newName>, <dropTarget>)
| Parameter | Description |
|---|---|
newName | The new collection name in the same database |
dropTarget | Optional, default false. If true, an existing collection called newName is dropped first and replaced |
2. Renaming a Collection
use bookstore
db.usr.insertOne({ name: "Aditi" })
db.usr.renameCollection("users")
// { ok: 1 }
show collections
// users
db.users.find()
// [ { _id: ObjectId('...'), name: 'Aditi' } ]
Within one database, a rename only changes metadata. It is fast even for very large collections, and indexes, validation rules and other options move with the collection.
3. Replacing an Existing Collection
By default, renaming onto a name that already exists fails with a target namespace exists error. Pass true as the second argument to replace it:
// Build a fresh version of a lookup table, then swap it in
db.countries_new.insertMany([
{ _id: "IN", name: "India" },
{ _id: "PT", name: "Portugal" }
])
db.countries_new.renameCollection("countries", true)
// the old "countries" collection is dropped and replaced
This "build then swap" pattern is useful for reference data that is rebuilt periodically: readers see either the complete old version or the complete new one, never a half-loaded collection.
dropTarget: true, the old target collection and all its documents are deleted permanently. Make sure that is what you want.4. Moving a Collection to Another Database
The shell method only renames within a database. To move a collection into a different database, use the renameCollection administrative command, which must run against the admin database and uses full namespaces:
db.adminCommand({
renameCollection: "bookstore.orders_2023", // source: database.collection
to: "archive.orders_2023", // target: database.collection
dropTarget: false
})
Moving between databases is very different from a simple rename:
- MongoDB copies every document and rebuilds every index in the target database, then drops the source. For a large collection this takes time and resources.
- It needs privileges on both databases: reading and dropping the source collection, and inserting documents and creating indexes in the target. Cluster-wide roles such as
readWriteAnyDatabaseplusdbAdminAnyDatabasecover this. - It is not supported for sharded collections.
For big collections, mongodump and mongorestore with --nsFrom / --nsTo, or an aggregation ending in $out or $merge, give you more control. See Backup and Restore.
5. Restrictions
- You cannot rename views; drop and re-create them instead.
- You cannot rename system collections (names starting with
system.). - Sharded collections can be renamed within the same database (supported since MongoDB 5.0), but not moved to another database with this command.
- The new name must follow the normal collection naming rules.
6. Side Effects to Plan For
- Open change streams on the old collection are invalidated; consumers must reopen them on the new name.
- Running queries and cursors on the collection may fail with an error during the rename.
- Application code still using the old name will now write into a new, empty collection with that name, because writes create collections automatically.
- Views defined on the old name stop returning data until they are re-created against the new name.
- Permissions granted on the old collection name by custom roles must be updated.
show collections that no new collection has appeared under the old name.7. Renaming from Java
import com.mongodb.MongoNamespace;
import com.mongodb.client.*;
import com.mongodb.client.model.RenameCollectionOptions;
public class RenameCollectionExample {
public static void main(String[] args) {
try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
MongoCollection<org.bson.Document> usr = client.getDatabase("bookstore").getCollection("usr");
// Same database
usr.renameCollection(new MongoNamespace("bookstore", "users"));
// Another database, replacing the target if it exists
client.getDatabase("bookstore").getCollection("orders_2023")
.renameCollection(new MongoNamespace("archive", "orders_2023"),
new RenameCollectionOptions().dropTarget(true));
}
}
}
8. Summary
db.collection.renameCollection(newName)renames a collection within the same database, quickly and with its indexes and options.- Pass
trueas the second argument to replace an existing target collection. - Use
db.adminCommand({ renameCollection, to })to move a collection to another database; this copies the data. - Views and system collections cannot be renamed; sharded collections can be renamed only within their database.
- Update application code, change streams, views and roles that refer to the old name.