【笔记】初学mongodb之自定义类

本文介绍了一个使用 PHP 进行 MongoDB 数据操作的示例代码,包括连接数据库、选择数据库、进行基本的 CRUD 操作等。通过具体实例展示了如何更新文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
class MongoServer{
    private $server = 'localhost:27017';
    private $options = array('connect'=>true);

    public $client;
    public $db;
    public $dbname='test';

    public function __construct($server, $options=false, $dbname=''){
        $server && $this->server = $server;
        $dbname && $this->dbname = $dbname;
        $options && count($options) && $this->options = $options;
        $this->ConnectDb();
    }
    private function ConnectDb(){
        try{
            #链接数据库
            $this->client = new MongoClient($this->server, $this->options);
        }catch(Exception $e){
            exit('connect MongoDB failed!');
        }
        try{
            #选库
            $this->db = $this->client->selectDB($this->dbname);
        }catch(Exception $e){
            exit('select DataBase failed!');
        }
    }

    function table($name){
        $this->collect = $this->db->__get($name);
        return new MongoCURD($this->collect);
    }

}
class MongoCURD{
    public $table;
    function __construct($table){
        $this->table = $table;
    }

    public function select($map=array()){
        $cursor = $this->table->find($map);
        return iterator_to_array($cursor);
    }

    public function find($map=array()){
        $cursor = $this->table->findOne($map);
        return $cursor;
    }

    public function count(){
        return $this->table->count();
    }
    public function handsById($id, $action="find"){
        if(!(bool)$id){
            return false;
        }
        $mongoId = new MongoId($id);
        switch($action){
            case "delete":
                $rs = $this->table->remove(array('_id'=>$mongoId), array('justOne'=>true));
                if($rs['n']){
                    return $rs['n'];
                }else{
                    return false;
                }
                break;
            default:
                $cursor = $this->table->findOne(array('_id'=>$mongoId));
                return $cursor;
                break;
        }
    }
    public function update($map, $data, $isnew=false){
        return $this->table->update($map, $data, array('upsert'=>$isnew));
    }
    // 将id转成可查询对象
    public function mongoId($id){
        return new MongoId($id);
    }
}
function db($dbname){
    return new MongoServer('192.168.1.188:11001', false, $dbname);
}
$person = db('test')->table('person');
$map = array('_id'=>$person->mongoId('56ea176ba3f97f58350e653'));
$onedata = $person->find($map);
$onedata['age'] = 93;
$rs = $person->update($map, $onedata, true);

var_dump($rs);

exit;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值