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

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
