• 周六. 8月 20th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

PHP使用MongoDB(CRUD)

admin

11月 28, 2021
<?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:%[email protected]%s:27017", $params['db'], $params['pwd'], $params['uri']);
        $this -> manager = new MongoDBDriverManager($link);
        $this -> bulk = new MongoDBDriverBulkWrite;
        $this -> concern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::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 MongoDBDriverQuery($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 MongoDBDriverCommand(['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);

发表回复

您的电子邮箱地址不会被公开。