使用docker-compose部署mongo和mongo-express
docker-compose.yml
代码语言:javascript复制version: '3.8'
# 使用外部网络
# docker network create server_web-network
networks:
server_web-network:
external: true
services:
docker-mongo:
image: mongo:5.0.5
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 123456
ports:
- 27017:27017 #为了在宿主机使用vs code连接mongo
volumes:
- ./data:/data/db
networks:
- server_web-network
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: 123456
ME_CONFIG_MONGODB_URL: mongodb://root:123456@docker-mongo:27017/
networks:
- server_web-network
启动服务
代码语言:javascript复制docker-compose up -d
访问mongo-express
代码语言:javascript复制http://localhost:8081/
php extension and library
虽然可以单独使用扩展,但强烈建议用户一起使用扩展和库。该库提供了与其他 MongoDB 语言驱动程序一致的高级 API。
extension
代码语言:javascript复制# Dockerfile
...
RUN pecl install mongodb-1.12.0
&& docker-php-ext-enable mongodb
...
library
代码语言:javascript复制composer require mongodb/mongodb
php demo
代码语言:javascript复制<?php
require_once __DIR__ . '/../../vendor/autoload.php';
$collection = (new MongoDBClient('mongodb://root:123456@docker-mongo/'))->images->shop1;
$document=[
'content' => 'uuuu2',
'uri'=>'ss.jpg',
'create_time' => time(),
'update_time' => 0,
];
$updateResult = $collection->updateOne(
['_id' => md5(11)],
['$set' => $document],
['upsert' => true]
);
printf("Matched %d document(s)n", $updateResult->getMatchedCount());
printf("Modified %d document(s)n", $updateResult->getModifiedCount());
printf("Upserted %d document(s)n", $updateResult->getUpsertedCount());
$upsertedDocument = $collection->findOne([
'_id' => $updateResult->getUpsertedId(),
]);
var_dump($upsertedDocument);
//$document = $collection->findOne(['_id' => md5(11)]);
//
//var_dump($document->content);
//echo json_encode($document, JSON_UNESCAPED_UNICODE);
备份/恢复
mongodump 和mongorestore 是mongodb自带的工具,如果本地没有安装mongodb,可以单独下载 https://www.mongodb.com/try/download/database-tools
备份
代码语言:javascript复制docker exec -it {容器id} /bin/sh
cd /data/db
mkdir dump
mongodump -d {库名} -o ./dump -u root -p 123456 --authenticationDatabase admin
恢复
代码语言:javascript复制mongorestore -h 127.0.0.1:27017 -u root -p 123456 --authenticationDatabase admin --dir=/data/dump
参考
https://docs.mongodb.com/drivers/php/
https://docs.mongodb.com/php-library/current/tutorial/crud/