我正在尝试使用 Python 中的 Azure Cosmos DB 创建 MongoDB 数据库,但遇到了一些问题,并且在此过程中没有成功。
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'}"),)
我希望能够在 Python 中使用 Azure Cosmos DB 成功创建 MongoDB 数据库,并且不会出现任何错误。
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))
完整错误:{'ok':0.0,'errmsg':'无效的自定义操作:指定了CreateDatabaseCustomAction','code':59,'codeName':'CommandNotFound'}
当您尝试连接机器中同一端口上运行的 mongo 服务时,会出现上述错误。因此,请尝试在执行代码时关闭该服务。以下是在 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.")
输出:
欲了解更多信息,请参阅此文档。