thinkphp 5.0 增加mongodb 使用,配置方式如下,在config.php文件中追加
// mongo 数据库配置 'db_mongo' => [ 'type' => '\think\mongo\Connection', 'hostname' => '127.0.0.1', 'database' => 'test', 'username' => '', 'password' => '', 'hostport' => 27017, ],
如图所示
// CURD demo
<?php namespace app\index\controller; /** * Author: wongjull * Date: 2018/7/3 0003 * Time: 14:11 */ use think\Controller; use think\Db; use think\Request; class Test extends Controller { protected $mongoDb; public function __construct(){ $this->mongoDb = Db::connect("db_mongo"); } public function index(){ $data = array('name'=>'jiahe','email'=>'h@qq.com'); $test1= $this->mongoDb->name("test")->insert($data); var_dump($test1);exit; } // 添加数据 public function add(){ $title = Request::instance()->get('title'); if(!$title) exit('no title'); $data = [ 'author' => 'wjh', 'age' => '22', 'title' => $title, 'comment' => [ [ 'id' => '001', 'content' => 'double kill1' ] ], 'time' => time(), ]; $res = $this->mongoDb->name('testArr')->insert($data); if($res){ return json($res); }else{ echo "error"; } } // 查询 和多维情况的修改 public function select(){ // 排序 -1 倒序 1正序 $res = $this->mongoDb->name('testArr')->order(array('_id'=>-1))->limit('2')->select(); echo '<pre>'; print_r($res); $res = $this->mongoDb->name('testArr')->field('comment,time,_id')->find(); // 多维数据的修改 if($res){ echo '<pre>'; print_r($res['_id']);exit; var_dump($res['_id']);exit; $comment = $res['comment']; foreach($comment as $k => $v) { if($k == 0) { $comment[$k]['content'] = '00200被修改了'; } } $data['comment'] = [ '$set', $comment ]; $where = array('_id' => $res['_id']); $this->mongoDb->name('testArr')->where($where)->update($data); print_r('<pre>'); print_r($res); }else{ echo "error"; } } // push更新和pop更新 评论的追加 public function push() { $update_data['comment'] = [ '$push', // $pop 也是支持的 [ 'id' => '002', 'content' => '三杀' ] ]; $update_res = $this->mongoDb->name('testArr')->where('title','防塔与补兵')->update($update_data); if($update_res){ print_r('<pre>'); print_r($update_res); echo "success"; }else{ echo "error"; } } // 修改 public function update(){ $res = $this->mongoDb->name('testArr')->field('comment,time,_id')->find(); // 多维数据的修改 if($res){ echo '<pre>'; print_r($res['_id']);exit; var_dump($res['_id']);exit; $comment = $res['comment']; foreach($comment as $k => $v) { if($k == 0) { $comment[$k]['content'] = '00200被修改了'; } } $data['comment'] = [ '$set', $comment ]; $where = array('_id' => $res['_id']); $this->mongoDb->name('testArr')->where($where)->update($data); print_r('<pre>'); print_r($res); }else{ echo "error"; } } // 删除 public function del() { $where['_id'] = '5b3b443c8d908b2c84002d7a'; // project id 当做条件检索 $update_res = $this->mongoDb->name('testArr')->where($where)->delete(); var_dump($update_res); } // 测试传参 public function test() { $res = Request::instance()->param('_id','','strip_tags,strtoupper'); var_dump($res); } }