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:
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:
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:
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.