You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Azure Cosmos DB创建MongoDB数据库时遇到问题

Python操作Azure Cosmos DB MongoDB API创建数据库失败问题排查

问题描述

我在Python中尝试使用Azure Cosmos DB的MongoDB API创建数据库,但创建过程中报错,请求协助解决该问题。

已执行步骤

  • 尝试通过Python在Azure Cosmos DB中创建新的MongoDB数据库
  • 遵循Azure Cosmos DB官方文档配置MongoDB API
  • 创建过程中触发错误
  • 已尝试通过现有资源排查问题

错误信息

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数据库,无错误抛出

补充信息

  • 已成功连接到Cosmos MongoDB Server
  • 相关代码:
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.".format(self.db_name))

解决方案

1. 错误原因

报错是因为db.command({"customAction": "CreateDatabase"})属于Cosmos DB旧版自定义命令,当前MongoDB API已不再支持这种方式创建数据库,需遵循MongoDB原生语法操作。

2. 代码修改方案

方案一:通过创建集合自动生成数据库

Cosmos DB MongoDB API中,空数据库不会被list_database_names()返回,直接创建集合即可自动生成对应的数据库:

# 替换原代码中的db.command(...)部分
# 创建集合以触发数据库自动创建
db.create_collection("sample_collection")
logger.info(f"Created database {self.db_name} and collection sample_collection")

方案二:使用Azure Cosmos SDK创建带吞吐量的数据库

如果需要为数据库配置共享吞吐量,建议使用Azure Cosmos DB官方Python SDK:

from azure.cosmos import CosmosClient, DatabaseProxy

# 使用Cosmos DB端点和密钥初始化客户端
client = CosmosClient(self.cosmos_endpoint, self.cosmos_key)
# 创建带共享吞吐量的数据库(不存在则创建,存在则返回现有数据库)
db: DatabaseProxy = client.create_database_if_not_exists(
    id=self.db_name,
    offer_throughput=400  # 根据业务需求调整RU/s数值
)

3. 注意事项

  • 使用pymongo操作Cosmos DB MongoDB API时,优先使用MongoDB原生语法,避免使用Cosmos自定义命令;
  • list_database_names()仅返回包含至少一个集合的数据库,空数据库不会被列出,这是Cosmos DB的正常行为。

内容的提问来源于stack exchange,提问作者gluck0101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:33:29