Open In App

Python MongoDB- rename()

Last Updated : 02 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

rename() method in PyMongo is used to rename a collection within a MongoDB database. It allows you to change the name of an existing collection while keeping its data intact. This is useful for reorganizing or updating collection names without losing data.

Syntax

collection.rename(new_name, dropTarget=False)

Parameters:

  • new_name: new name for the collection.
  • dropTarget (optional): Set to True to overwrite an existing collection with the new name. Default is False.

Let's look at some examples to understand it better.

Example 1:

This example creates a collection and renames it from collection to collec. With dropTarget=True, any existing collec will be overwritten.

python
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
database = client['database']
collection = database['myTable']

docs = [{"id": 1, "name": "Drew"}, {"id": 3, "name": "Cody"}]
collection.insert_many(docs)

# Rename the collection to 'collec'
collection.rename('collec', dropTarget=True)

# List and print all collections in the database
r = database.list_collection_names():
for name in r:
    print(name)

Output

collec

Example 2 :

In this example, dropTarget is set to False, so the new collection name must be unique. Since collec already exists, an error will be raised.

python
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client['database']
collection = db['myTable']

docs = [{"id": 1, "name": "Drew"}, {"id": 3, "name": "Cody"}]
collection.insert_many(docs)

# Rename the collection to 'collec' (only if 'collec' does not already exist)
collection.rename('collec', dropTarget=False)

# List all collections in the database
for name in db.list_collection_names():
    print(name)

Output

pymongo.errors.OperationFailure: target namespace exists

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads