接入教程
1. 在AWS控制台创建DocumentDB集群
2. 配置安全组允许应用连接
3. 使用MongoDB驱动连接数据库
4. 执行CRUD操作管理JSON文档
5. 设置监控告警和自动备份
Python连接与查询示例
import pymongo
# 使用MongoDB兼容连接字符串
client = pymongo.MongoClient(
host="https://api.example.com",
port=27017,
username="YOUR_API_KEY",
password="YOUR_API_KEY",
tls=True
)
# 选择数据库和集合
db = client['sample_database']
collection = db['sample_collection']
# 插入文档
document = {"name": "test", "value": 123}
result = collection.insert_one(document)
print(f"插入文档ID: {result.inserted_id}")
# 查询文档
query_result = collection.find_one({"name": "test"})
print(f"查询结果: {query_result}")
PHP连接与插入示例
<?php
require_once 'vendor/autoload.php';
$client = new MongoDB\Client(
'mongodb://YOUR_API_KEY:YOUR_API_KEY@https://api.example.com:27017/?tls=true'
);
// 选择数据库和集合
$db = $client->selectDatabase('sample_database');
$collection = $db->selectCollection('sample_collection');
// 插入文档
$document = ['name' => 'test', 'value' => 123];
$result = $collection->insertOne($document);
echo "插入文档ID: " . $result->getInsertedId() . "\n";
// 查询文档
$queryResult = $collection->findOne(['name' => 'test']);
echo "查询结果: " . print_r($queryResult, true) . "\n";
JavaScript连接与更新示例
const { MongoClient } = require('mongodb');
async function main() {
const uri = 'mongodb://YOUR_API_KEY:YOUR_API_KEY@https://api.example.com:27017/?tls=true';
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('sample_database');
const collection = db.collection('sample_collection');
// 插入文档
const document = { name: 'test', value: 123 };
const insertResult = await collection.insertOne(document);
console.log(`插入文档ID: ${insertResult.insertedId}`);
// 更新文档
const updateResult = await collection.updateOne(
{ name: 'test' },
{ $set: { value: 456 } }
);
console.log(`更新文档数: ${updateResult.modifiedCount}`);
} finally {
await client.close();
}
}
main().catch(console.error);
常见问题
Amazon DocumentDB与MongoDB的兼容性如何?
Amazon DocumentDB实现了MongoDB 4.0和5.0的API核心功能,支持大多数MongoDB驱动程序、查询语言和工具。但某些特定功能如服务器端JavaScript执行、某些聚合管道阶段可能不完全支持。建议查阅AWS官方文档了解详细的兼容性信息。
连接Amazon DocumentDB需要哪些凭证?
连接Amazon DocumentDB需要以下凭证:数据库实例终端节点(主机名)、端口号(默认27017)、主用户名和密码。这些凭证在创建数据库实例时设置,并通过AWS Secrets Manager或IAM数据库身份验证进行管理。连接时必须启用TLS加密。
如何确保连接安全性?
为确保连接安全性,必须:1. 始终使用TLS/SSL加密连接;2. 将数据库实例部署在私有子网中;3. 通过安全组和网络ACL限制访问来源;4. 定期轮换数据库凭证;5. 使用IAM角色进行身份验证;6. 启用审计日志监控访问行为。
Aitishiku.com