w3resource

MongoDB: db.collection.renameCollection() method

db.collection.renameCollection

The db.collection.renameCollection() method is used to rename a collection.

Syntax:

db.collection.renameCollection(target, dropTarget)

Parameters:

Name Description Required /
Optional
Type
target The new name of the collection. Enclose the string in quotes. Required string
dropTarget If true, mongod drops the target of renameCollection prior to renaming the collection. The default value is false. Optional boolean

Limitations

  • db.collection.renameCollection() cannot move a collection between databases. Use renameCollection for these rename operations.
  • db.collection.renameCollection() is not supported on sharded collections.

The db.collection.renameCollection() method operates within a collection by changing the metadata associated with a given collection.

Example: MongoDB: db.collection.renameCollection() method

Here we the list of collections.

> show collections;
restaurants
restaurants1
system.indexes
userdetails

The following statement will rename the collection restaurants1 to restaurants_new.

db.restaurants1.renameCollection("restaurants_new");

Output:

> db.restaurants1.renameCollection("restaurants_new");
{ "ok" : 1 }

Here we the list of collections after rename.

> show collections;
restaurants
restaurants_new
system.indexes
userdetails

Retrieve the restaurants data from here

Previous: db.collection.remove() method
Next: db.collection.save() method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/shell-methods/collection/db-collection-renameCollection.php