Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython MongoDB- rename()

Python MongoDB- rename()

MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB and Python for an in-depth introduction to the topic. Now let’s understand the use of rename() function in PyMongo.

rename()

The PyMongo function rename() is used to rename a collection. The rename operation fails if the new name is not an instance of basestring or it is an invalid collection name.

Syntax : rename(new_name, session = None, **kwargs)
Parameters :

  • new_name : The new name of the collection.
  • session : (Optional) a ClientSession.
  • **kwargs : (Optional) additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. dropTarget = True).

Example 1 : In this example we will create a collection and rename it. The rename() function will rename the collection name from collection to collec. The value of dropTarget is set as True, this means that if an existing collection collec existed, then the new collection would overwrite the existing collection’s data.




# importing the module
from pymongo import MongoClient
  
# creating a MongoClient object 
client = MongoClient() 
    
# connecting with the portnumber and host 
client = MongoClient("mongodb://localhost:27017/"
  
# accessing the database 
database = client['database']   
  
# access collection of the database 
collection = database['myTable'
docs = [{"id":1, "name":"Drew"},
        {"id":3, "name":"Cody"}]
collection.insert_many(docs)
  
# renaming the collection
collection.rename('collec', dropTarget = True)
  
result = database.collection_names()
for collect in result:
    print(collect)


Output-

collec

Example 2 : In this example, the dropTarget parameter is set to False, the new collection name entered should be unique. But since the collection name collec already exists in the database, it will return an error.




# importing the module
from pymongo import MongoClient
  
# creating a MongoClient object 
client = MongoClient() 
    
# connecting with the portnumber and host 
client = MongoClient("mongodb://localhost:27017/"
  
# accessing the database 
database = client['database'
    
# access collection of the database 
mycollection = database['myTable'
docs = [{"id":1, "name":"Drew"},
        {"id":3, "name":"Cody"}]
mycollection.insert_many(docs)
  
# renaming the collection
mycollection.rename('collec', dropTarget = False)
  
result = database.collection_names()
for collect in result:
    print(collect)


Output :

pymongo.errors.OperationFailure: target namespace exists

RELATED ARTICLES

Most Popular

Recent Comments