Using renameCollection() In MongoDB

The renameCollection() method in MongoDB is used to rename an existing collection within the same database.

Syntax:

db.collection.renameCollection( newName, { dropTarget: <boolean> } )

Explanation:

  • db is the database object.
  • collection is the existing collection object.
  • newName is the new name for the collection.
  • dropTarget is an optional parameter that specifies whether to drop the target collection if it already exists. The default value is false.

Examples of renameCollection():

Suppose we have a gfg database in courses collection which stores information about various courses. Each document in the collection represents a course and contains details such as the course name, Instructor name, fees, and duration.

After creating collections in gfg database looks like:

collections

Example 1: Rename the courses collection to new_courses:

Let’s rename the collection name from courses collection to new_courses collection.

Query:

db.courses.renameCollection("new_courses", { dropTarget: true })

Output:

new_courses

Example 2: Rename the new_courses collection to top_courses”

Let’s rename the collection name from new_courses collection to top_courses.

Query:

db.new_courses.renameCollection("top_courses", { dropTarget: true })

Output:

top_courses

Note: renameCollection cannot be used to move collections between databases.

How to Rename Collection in MongoDB?

Renaming a collection in MongoDB is a common task faced by developers and database administrators. In this article, we will learn the different methods to rename a collection in MongoDB, including the renameCollection() method and the db.runCommand() method. By the end of this article, we will have a clear understanding of how to rename a collection in MongoDB.

Similar Reads

How to Rename Collection in MongoDB?

When working with MongoDB, there are times when we may need to rename a collection. This can be due to changes in our application’s data model or for organizational purposes. Below are the methods that help us to Rename Collection in MongoDB by queries as follows:...

1. Using renameCollection()

The renameCollection() method in MongoDB is used to rename an existing collection within the same database....

2. Using db.runCommand()

The db.runCommand() method is a powerful tool that allows us to execute complex MongoDB commands directly from the MongoDB shell or from within your application code...

Conclusion

Overall, Renaming collections in MongoDB is a common task that can be easily solve using the renameCollection() method and the db.runCommand() method. These methods provide flexibility and allowing developers and database administrators to rename collections without losing any data....