在EC2上使用Amazon DocumentDB

安装Mongo shell。

在 EC2 上运行以下命令。

echo -e "[mongodb-org-3.6] \nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/amazon/2013.03/mongodb-org/3.6/x86_64/\ngpgcheck=1 \nenabled=1 \ngpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc" | sudo tee /etc/yum.repos.d/mongodb-org-3.6.repo 

yum install -y mongodb-org-shell

检查mongo shell的运行情况

wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem

mongo --ssl --host xxx.ap-northeast-1.docdb.amazonaws.com:27017 --sslCAFile rds-combined-ca-bundle.pem --username your_name --password your_password

※ 替换 xxx.ap-northeast-1.docdb.amazonaws.com 部分为您的 DocumentDB 集群的终端节点。
※ 替换 your_name 部分为您创建 DocumentDB 时使用的用户名。
※ 替换 your_password 部分为您创建 DocumentDB 时使用的密码。

安装php-pecl-mongodb模块。

★ php 已经在 remi 存储库中安装完成。

一开始,我用以下命令进行了执行。

yum install --disablerepo=amzn-main --enablerepo=remi-php70 php-pecl-mongodb

然而,由于缺少scl-utils错误,因此需要先添加软件包。

rpm -Uvh ftp://ftp.scientificlinux.org/linux/scientific/6.4/x86_64/updates/fastbugs/scl-utils-20120927-8.el6.x86_64.rpm

我再次执行了以下命令。

yum install --disablerepo=amzn-main --enablerepo=remi-php70 php-pecl-mongodb

但是,由于出现了找不到snappy错误,因此请删除–disablerepo=amzn-main并运行。

yum install --enablerepo=remi-php70 php-pecl-mongodb

对php-pecl-mongodb进行验证

$dns = 'mongodb://your_name:your_password@xxx.ap-northeast-1.docdb.amazonaws.com:27017/?replicaSet=rs0';
$urlOptions = [
    'ssl' => true
];
$driverOptions = [
    'ca_file' => '/path/to/rds-combined-ca-bundle.pem'
];

$manager = new \MongoDB\Driver\Manager($dns, $urlOptions, $driverOptions);

$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->insert(['name' => 'qiita']);
$manager->executeBulkWrite('database_name.collection_name', $bulk);

如果设置以下内容,会在错误日志中输出调试信息,这对于无法连接的情况可能会有所帮助。

ini_set('mongodb.debug', 'stderr');

使用公式库

composer require mongodb/mongodb
$dns = 'mongodb://your_name:your_password@xxx.ap-northeast-1.docdb.amazonaws.com:27017/?replicaSet=rs0'
$uriOptions = ['ssl' => true];
$driverOptions = ['ca_file' => '/path/to/rds-combined-ca-bundle.pem'];

$client = new \MongoDB\Client($dns, $uriOptions, $driverOptions);
$db = $client->selectDatabase('database_name');
$collections = $db->listCollections();

从本地机器连接(图形用户界面)

使用MongoDB Compass,您可以通过SSH连接和EC2跳板以及SSL证书进行连接。