tp6使用MongoDB需要配置复制集:
配置方法链接
将单节点转为复制集 — MongoDB Manual 3.4 (mongoing.com)
tp6数据库配置文件内容:
database.conf
'mongodb'=>[ // 数据库类型 'type' => 'mongo', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'testdb', // 用户名 'username' => 'root', // 密码 'password' => '123456', // 端口 'hostport' => '27017', // 数据库连接参数 'params' => [], // 数据库调试模式 'debug' => env('database.debug', true), // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'deploy' => 0, // 数据库读写是否分离 主从式有效 'rw_separate' => false, // 监听SQL 'trigger_sql' => true, // 读写分离后 主服务器数量 'master_num' => 1, // 指定从服务器序号 'slave_no' => '', // 是否严格检查字段是否存在 'fields_strict' => true, // 是否需要断线重连 'break_reconnect' => false, // 字段缓存路径 'schema_cache_path' => app()->getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR, ]
Db类查询数据:
$data = Db::connect('mongodb') ->table('user_info') ->withoutField('_id,device_id') ->where(['device_id' => '1234567']) ->select(); return json($data);
原子操作:
Db::connect('mongodb') ->table('user_info') ->where(['uid'=>['=',1]]) ->update(['test_col'=>['$set',['field_1'=>1,'field_2'=>2]]]);
$set
用来指定一个键并更新键值,若键不存在并创建。
原子操作常用命令
MongoDB 原子操作 | 菜鸟教程 (runoob.com)
修改内嵌文档内容:
Db::connect('mongodb') ->table('user_info') ->where(['uid'=>['=',1]]) ->update(['test_col.field_1'=>3);