PHP Mongodb使用
docker安装mongodb
-
vim docker-compose.yml
version: "3"
services:
mongo:
image: mongo
container_name: mongo_1 #容器名
# restart: always
# command:
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=123456
ports:
- 17017:27017
-
docker-compose up
-
查看是否启动 docker ps 或 docker ps |grep mongo_1
-
安装mongodb.so
需先安装openssl
(不安装php客户端连接会报:PHP Fatal error: Uncaught MongoDB\Driver\Exception\AuthenticationException: The “SCRAM-SHA-1” authentication mechanism requires libmongoc built with –enable-ssl )
执行:
apt-get install openssl
apt-get install libssl-dev #这里要是需要先安装依赖 可以先
apt-get update 更新一下来源 使用 apt-get install libssl1.0-dev
-
进入容器(php)安装扩展
1. docker exec -it web_php71_1 /bin/bash
2. pecl install mongodb
3. docker-php-ext-enable mongodb
成功后如下:
-
php使用
poser require mongodb/mongodb
$client = new Client('mongodb://root:123456@192.168.3.35:17017/admin?');
$collection = $client->sjx_video->follow;
$insertOneResult = $collection->insertOne([
'ids' => Functions::dBIncrementTransmitter(),
'member_ids' => 1,
'follow_member_ids' => 2,
'status' => 1,
'created_at' => date('Y-m-d H:i:s'),
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
写入成功