1. 程式人生 > 其它 >PHP使用MongoDB(CRUD)

PHP使用MongoDB(CRUD)

<?php

//配置
$config = [
    'db' => 'test',
    'pwd' => 'test12345',
    'uri' => '127.0.0.1',
];

function dd($data)
{
    echo '<pre>';
    print_r($data);
}
//定義測試資料
$user_list = [
    [
        'id' => 1,
        'name' => '劉備',
        'mobile' => '13111111111',
        'age' => 20,
        'gender' => 1,
        'pic' => '/web/uploads/pic/20210803123456.jpg'
    ]
, [ 'id' => 2, 'name' => '關羽', 'mobile' => '13111111112', 'age' => 26, 'gender' => 1, 'pic' => '/web/uploads/pic/20210803123457.jpg' ], [ 'id' => 3, 'name' => '西施', 'mobile' => '13111111113', 'age' => 16, 'gender' => 2, 'pic' => '/web/uploads/pic/20210803123458.jpg' ]
, [ 'id' => 4, 'name' => '貂蟬', 'mobile' => '13111111114', 'age' => 18, 'gender' => 2, 'pic' => '/web/uploads/pic/20210803123459.jpg' ] ]; class Mongo { private $manager; private $bulk; private $concern; private $table
; private $collection; private $db; public function __construct($params, $collection) { $link = sprintf("mongodb://%s:%s@%s:27017", $params['db'], $params['pwd'], $params['uri']); $this -> manager = new MongoDB\Driver\Manager($link); $this -> bulk = new MongoDB\Driver\BulkWrite; $this -> concern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可選,修改確認 $this -> db = $params['db']; $this -> table = sprintf("%s.%s", $params['db'], $collection); $this -> collection = $collection; } /** * 新增 */ public function add($data = []) { foreach($data as $item) { $this -> bulk -> insert($item); } $result = $this -> manager -> executeBulkWrite($this -> table, $this -> bulk, $this -> concern); return $result -> getInsertedCount(); } /** * 查詢 */ public function get($where = [],$options=[]) { $query =new MongoDB\Driver\Query($where, $options); $cursor = $this -> manager -> executeQuery($this->table,$query); $data = []; if(!empty($cursor)) { foreach($cursor as $item) { $data[] = $item; } } return $data; } /** * 修改 */ public function edit($where=[],$update=[],$upsert=false) { $this->bulk->update($where,['$set' => $update], ['multi' => true, 'upsert' => $upsert]); $result = $this->mongodb->executeBulkWrite($this->table, $this->bulk, $this->writeConcern); return $result->getModifiedCount(); } /** * 刪除 */ public function delete($where=[], $limit=1) { $this -> bulk -> delete($where, ['limit'=>$limit]); $result = $this -> manager -> executeBulkWrite($this->table, $this->bulk, $this->writeConcern); return $result -> getDeletedCount(); } /** * 獲取滿足條件的資料總數 */ public function getCount($where=[]) { $command = new MongoDB\Driver\Command(['count' => $this->collection,'query'=>$where]); $result = $this -> manager -> executeCommand($this->db,$command); $res = $result->toArray(); $cnt = 0; if ($res) { $cnt = $res[0]->n; } return $cnt; } /** * 分頁獲取資料 */ public function page($where=[],$page=1,$limit=10,$sort=['id'=>1]) { $count = $this->getCount($where); $data['count'] = $count; $totalpage = ceil($count / $limit); if ($page>$totalpage) { $page = $totalpage; }elseif ($page <1) { $page = 1; } $skip = ($page-1)*$limit; $options = [ 'skip' => $skip, 'limit' => $limit, 'sort' => $sort, ]; $data['data'] = $this->get($where, $options); $data['cur_page'] = $page; $data['total_page'] = $totalpage; return json_encode($data); } } //例項化物件 $obj = new Mongo($config,'users'); //查詢 //大於,按年齡升序排 $result = $obj -> get(['id' => ['$gt'=>0]], ['sort' => ['age' => 1]]); //1-升序 -1-降序 dd($result); //大於等於 $result = $obj -> get(['id' => ['$gte'=>2]], ['sort' => ['age' => 1]]); dd($result); //小於 $result = $obj -> get($filter = ['age'=>['$lt'=>30]], ['projection'=>[]]); dd($result); //小於等於 $result = $obj -> get($filter = ['age'=>['$lte'=>20]]); dd($result); //不設條件查詢 $result = $obj -> get($filter = [], $options=[]); //in查詢,不顯示_id $result = $obj -> get(['id'=>['$in'=>[1,2]]],['projection'=>['_id'=>0]]); dd($result); //not in查詢 精確查詢欄位 $result = $obj -> get(['id'=>['$nin'=>[1,2]]],['projection'=>['_id'=>0,'name'=>1,'id'=>1]]); dd($result); //like查詢 $result = $obj -> get(['name'=>['$regex'=>'^西']]); dd($result); //查詢數量 $result = $obj -> getCount(); dd($result); //分頁 $result = $obj -> page($filter = ['gender'=>1], 1, 2); dd(json_decode($result,true)); //新增 $result = $obj->add($user_list); dd($result); //修改 $result = $obj -> edit( ['id'=>1], ['$set' => ['age'=>30, 'weapon'=>'丈八蛇矛']] ); dd($result); //刪除 $result = $obj -> delete(['id'=>5]); dd($result);