MongoDB Rename Collection



MongoDB Rename Collection

In MongoDB, the renameCollection operation is used to rename an existing collection. This method is essential for reorganizing and managing collection names within MongoDB databases.


Syntax

db.collection.renameCollection(newName, options)

The renameCollection method takes a newName to specify the new name for the collection and an optional options parameter to customize the renaming process.


Example MongoDB Rename Collection

Let's look at an example of how to use the renameCollection method in MongoDB:

1. Rename an Existing Collection

db.programGuru.renameCollection("newProgramGuru")

This command renames the programGuru collection to newProgramGuru.


Full Example

Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and renaming the collection.

Step 1: Switch to a Database

This step involves switching to a database named myDatabase.

use myDatabase

In this example, we switch to the myDatabase database.

MongoDB Rename Collection

Step 2: Create a Collection

This step involves creating a new collection named programGuru in the myDatabase database.

db.createCollection("programGuru")

Here, we create a collection named programGuru.

MongoDB Rename Collection

Step 3: Insert Documents into the Collection

This step involves inserting documents into the programGuru collection.

db.programGuru.insertMany([
    { name: "John Doe", age: 30, email: "john.doe@example.com" },
    { name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
    { name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])

We insert multiple documents into the programGuru collection.

MongoDB Rename Collection

Step 4: Rename the Collection

This step involves using the renameCollection method to rename the programGuru collection to newProgramGuru.

db.programGuru.renameCollection("newProgramGuru")

We rename the programGuru collection to newProgramGuru.

MongoDB Rename Collection

Conclusion

The MongoDB renameCollection operation is crucial for reorganizing and managing collection names within databases. Understanding how to use this method allows you to efficiently manage and maintain the structure of your MongoDB collections.