A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-mongodb-rename/ below:

Python MongoDB- rename() - GeeksforGeeks

Python MongoDB- rename()

Last Updated : 15 Jul, 2025

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:

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4