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.
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)
- 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.
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.
pymongo.errors.OperationFailure: target namespace exists