- 先配置MongoDB
在/config/database.php文件中增加以下内容
// 更多的数据库配置信息
'mongo' => [
// 数据库类型
'type' => env('mongo.type', 'mongo'),
// 服务器地址
'hostname' => env('mongo.hostname', '127.0.0.1'),
// 数据库名
'database' => env('mongo.database', 'tests'),
// 用户名
'username' => env('mongo.username', 'root'),
// 密码
'password' => env('mongo.password', '123456'),
// 端口
'hostport' => env('mongo.hostport', 27017),
// 数据库连接参数
'params' => [],
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 是否需要断线重连
'break_reconnect' => false,
// 监听SQL
'trigger_sql' => env('app_debug', true),
// 开启字段缓存
'fields_cache' => false,
// 字段缓存路径
'schema_cache_path' => app()->getRuntimePath() . 'mongodb' . DIRECTORY_SEPARATOR,
]
- 使用
在控制器中使用
use think\facade\Db;
public function index()
{
Db::connect('mongo')->table('test')->insert([
'name' => 'zhangsan'
]);
$table = Db::connect('mongo')->table('test')->select();
halt($table);
}
- 结果
- 可能发生的错误
No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling hello on '18.71.88.240:27017']
起先出现这个错误的时候我其实就是用127.0.0.1
连接,但是不知道为什么会报错,也许服务器有缓存?也或许是某个配置没有生效?后面改成服务器ip
连接还是报错,最后重装了服务器系统,重新搭建了环境使用127.0.0.1
连接就成功了