I am trying to create a MongoDB database using Azure Cosmos DB in Python, but I encountered some issues and was unsuccessful in the process.
2024-04-04 22:43:09 [INFO ] cl_cosmos_mongo_db.py:__mongo_connect - CosmosMongoDB Server Connected.
2024-04-04 22:43:09 [CRITICAL] cl_cosmos_mongo_db.py:__mongo_connect - The user_data database does not exist.
2024-04-04 22:43:09 [INFO ] cl_cosmos_mongo_db.py:__mongo_connect - Creating user_data database.
Arguments: (OperationFailure("Invalid custom action: CreateDatabaseCustomAction specified, full error: {'ok': 0.0, 'errmsg': 'Invalid custom action: CreateDatabaseCustomAction specified', 'code': 59, 'codeName': 'CommandNotFound'}"),)
I expected to successfully create a MongoDB database using Azure Cosmos DB in Python without any errors.
self.client = MongoClient(self.mongo_uri)
# Test the connection by accessing a database (e.g., admin)
self.client.admin.command('ismaster')
logger.info("CosmosMongoDB Server Connected.")
# Access the database
db = self.client[self.db_name]
# Check if the database exists
db_list = self.client.list_database_names()
if self.db_name in db_list:
logger.info(f"The {self.db_name} database exists.")
else:
logger.critical(f"The {self.db_name} database does not exist.")
logger.info(f"Creating {self.db_name} database.")
db.command({"customAction": "CreateDatabase"})
print("Created db '{}' with shared throughput.\n".format(self.db_name))
full error: {'ok': 0.0, 'errmsg': 'Invalid custom action: CreateDatabaseCustomAction specified', 'code': 59, 'codeName': 'CommandNotFound'}
The above error occurs when you try to connect mongo service which was running on the same port in the machine. So, try to shut down that service while you are executing your code. Below is one of the approach to create database in Azure Cosmos Mongo DB API.
from pymongo import MongoClient
mongo_uri = "*****"
client = MongoClient(mongo_uri)
db = client['database01']
if db.list_collection_names():
print("The 'database01' database is already exists.")
else:
print("The 'database01' database does not exist.")
db.create_collection('test_collection')
print("Created 'database01' database.")
Output:
For more information, refer to this document.