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);