php 操作mongodb

在这里首先说一下mongo 客户端安装完成有时会启动失败     这里解决办法就是 删除 D:\mongodb\db 下的 mongod.lock文件即可 再重新启动

首先下载mongodb php扩展

   5.3 mongo driver下载:   更多版本  https://github.com/mongodb/mongo-php-driver/downloads
  http://downloads.mongodb.org/mongo-latest-php5.3vc6ts.zip

把DLL复制到extension目录,然后   如我安装时wamp集成环境  我得扩展目录是 E:\wamp\bin\php\php5.4.16\ext

接下来我们修改php.ini   如我的目录:E:\wamp\bin\php\php5.4.16\php.ini  添加  extension=php_mongo.dll即可

接下来就是操作mongodb了 :我这以我的程序为例

  这里我的程序使用框架是yii     您不必理会框架本身

  

php 操作mongodb
<?php
header("Content-type:text/html;charset=utf-8;");
class CommentController extends Controller {
    public $layout = false;
    /**
     * Mongodb 连接句柄
     *
     * @var $conn
     */
    public $conn;

    /**
     * 评论表空间
     *
     * @var $collection
     */
    public $collection;

    /**
     * 关系表空间
     *
     * @var $commentIndex
     */
    public $commentIndex;

    /**
     * 评论关系总表 结果集
     *
     * @var $relation
     */
    private $relation;

    /**
     * 加工后关系列表
     *
     * @var $relation_list
     */
    private $relation_list = array ();

    /**
     * page 当前页数
     *
     * @var $page
     */
    public $page = 1;

    /**
     * limit 最大页码数
     *
     * @var $limit
     */
    public $limit = 10;

    /**
     * query 关键词搜索
     *
     * @var $query
     */
    public $query;

    /**
     * yii pageObject
     */
    public $pageObject = NULL;

    /**
     * 删除关系list
     *
     * @var $deletelist
     */
    private $deletelist = array ();

    /**
     * 删除关系result
     *
     * @var $result
     */
    private $result = array ();

    /**
     *  评论总数
     *
     *  @var $c_count
     */
    public $c_count;

    /**
     * Log 日志
     *
     * @var $Log
     */
    private $Log = NULL;


    /**
     *  cArrayDataProvider
     *
     *  @var cArrayDataProvider
     */
    public $cArrayDataProvider = NULL;
    /**
     * @初始化应用数据
     */
    public function init() {
        $this->layout = false;
        parent::init ();
        $this->mongoInit ();
        ini_set ( ‘memory_limit‘, ‘1024M‘ );
        $this->page = Yii::app ()->request->getParam ( ‘page‘, $this->page );
        $this->limit = Yii::app ()->request->getParam ( ‘limit‘, $this->limit );
    }
    /**
     * 数据库初始化,正式项目在配置文件中生成
     * @mongodb
     */
    public function mongoInit() {
        try {
            $this->conn = new MongoClient ( Yii::app ()->params [‘host‘] );
            $this->collection = $this->conn->selectCollection ( Yii::app ()->params [‘database‘], Yii::app ()->params [‘comment‘] );
            $this->commentIndex = $this->conn->selectCollection ( Yii::app ()->params [‘database‘], Yii::app ()->params [‘commentIndex‘] );
        } catch ( MongoConnectionException $e ) {
            exit ( ‘<p>Couldn\‘t connect to mongodb, is the "mongo" process running?</p>‘ );
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this -> c_count = $this->collection->count ();
        if ($this -> c_count) {
            $this->getCommentItem ( $this -> c_count );
            //$data = array(‘pages‘ => $this->pageObject, ‘total‘ => $this->c_count, ‘countPage‘ => $countPage);
        } else {
            //$data = array (‘pages‘ => $this->pageObject, ‘total‘ => 0, ‘countPage‘ => 0);
        }
        $this->render(‘list‘);
    }

    /**
     *  load CArrayDataProvider
     */
    protected function cArrayDataProvider(){
        $this -> cArrayDataProvider = new CArrayDataProvider($this -> relation_list,array(  
                            ‘keyField‘=>false,
            ));

        return $this -> cArrayDataProvider;
    }


    /**
     * 评论的所有数据集
     *
     * @throws Excepition
     */
    public function getCommentItem($count) {
        $this->cPagination ( $count );
        $page = ($this->page - 1) * $this->limit;
        $rows = $this->collection->find ()->sort ( array (‘_id‘ => - 1 ))->limit ( $this->limit )->skip ( $page  );
        $this->relation_list = $this->_page ( $rows );
        $this -> cArrayDataProvider();
        return $this->relation_list;
    }

    /**
     * yii分页
     *
     * @param
     * $count
     */
    protected function cPagination($count = 0) {
        $criteria = new CDbCriteria ();
        $pager = new CPagination ( $count ? $count : $this->c_count );
        $pager->pageSize = $this->limit;
        $pager->applyLimit ( $criteria );
        $this->pageObject = $pager;
        return $this->pageObject;
    }

    /**
     * 关键词搜索
     */
    public function actionSearch() {
        $k = Yii::app ()->request->getParam ( ‘k‘, NULL );
        if (empty ( $k )) {
            Yii::app ()->user->setFlash ( ‘error‘, "搜索关键词为空!" );
            $this->redirect ( Yii::app ()->request->urlReferrer );
        }

        $this->query = array ("comment" => new MongoRegex ( "/{$k}/" ) );

        $this -> c_count = $this->collection->find ( $this->query )->count ();
        if ($this -> c_count) {
            $this->cPagination ( $this -> c_count );
        }
        $page = ($this->page - 1) * $this->limit;
        $rows = $this->collection->find ( $this->query )->sort(array(‘_id‘ => -1))->limit ( $this->limit )->skip ( $page );
        $this->relation_list = $this->_page ( $rows );

        $this -> cArrayDataProvider();
        $this->render(‘list‘);
    }

    /**
     * 数据集处理
     *
     * @param array $rows
     * @param boolean $handle
     */
    protected function _page($rows, $handle = false) {
        $rows_list = array ();
        foreach ( $rows as $val ) {
            $rows_list [] = $val;
        }
        unset ( $rows );
        if (! $handle) {
            return $rows_list;
        }
        return array_slice ( $rows_list, ($this->page - 1) * $this->limit, $this->limit );
    }

    /** 
    * 用于构造提示信息的主体
    * $word 分类
    * $tip  提示信息
    * $color blue or red
    *
    */
    protected function dialogContent($word,$tip,$color) {
        switch($color) {
            case ‘red‘:
                $str = ‘<p>‘.$word.‘<font style="color:red">‘.$tip.‘</font></p>‘;
                break;
            case ‘blue‘:
                $str = ‘<p>‘.$word.‘<font style="color:blue">‘.$tip.‘</font></p>‘;
                break;
            default:
                $str = ‘<p>‘.$word.‘<font style="color:blue">‘.$tip.‘</font></p>‘;
                break;
        }   
        return $str;
    }

    /**
     * 删除评论
     */
    public function actionRemove() {
        $data = Yii::app ()->request->getParam ( ‘data‘, NULL );
        if (empty ( $data )) {
            exit($this -> dialogContent(‘批量删除‘, ‘数据有问题!‘, ‘red‘));
        }
        if (is_array ( $data )) {
            foreach ( $data as $k => $v ) {
                try {
                    $this->collection->remove ( array (‘_id‘ => ( object ) new MongoId ( $v[‘_id‘] ) ) );
                    $this->delCommentRelation ( ‘0883B740-C3AE-8EF0-C03E-15128FEF6142‘, $v [‘id‘] );
                    //增加日志
                    $this->Log = new Log; //解决批量插入问题
                    date_default_timezone_set(‘PRC‘); //设置时区
                    $operate_id = 2;
                    $this->Log->attributes = array(
                      ‘operate_id‘ => $operate_id, //操作人id
                      ‘uid‘    => 2, //用户uid
                      ‘type‘ => ‘删除‘, //日志类型 删除
                      ‘date‘ => date(‘Y-m-d H:i:s‘, time()),  //操作时间
                      ‘detail‘ => ‘操作人:‘.$operate_id.‘删除了帖子id:‘.$v [‘id‘] //详细
                    );
                    $this->Log->save();
                } catch ( Exception $e ) {
                    echo $e->getMessage () . ‘<br>‘ . $e->getFile () . ‘<br>‘ . ‘第‘ . $e->getLine () . ‘行<br>‘;
                }
            }
            unset ( $data );
        } else {
            throw new Exception ( ‘删除数据有问题,请查看程序‘ );
        }
        exit($this -> dialogContent(‘批量删除‘, ‘删除评论成功!‘, ‘blue‘));
    }

    /**
     * 删除关系入口
     *
     * @param int $id
     * @param int $delid
     */
    public function delCommentRelation($id, $delid) {
        $this->query = array (‘_id‘ => $id );
        $this->relation = $this->commentIndex->findOne ( $this->query );
        $this->relation_list = $this->relation [‘index‘];
        foreach ( $this->relation_list as $value ) {
            $this->deletelist [] = array_diff ( explode ( ‘_‘, $value ), array ($delid ) );
        }
        $this->deleteRelation ( $id );
    }
    // 删除关系
    public function deleteRelation($id) {
        foreach ( $this->deletelist as $key => $value ) {
            if (! empty ( $value )) {
                $this->result [] = implode ( ‘_‘, $value );
            }
        }
        $this->result = array_unique ( $this->result ); // 楼层唯一性显示
        $this->c_count = count ( $this->result );
        $this->updateRelation ( $id );
    }
    // 更新
    public function updateRelation($id) {
        $set = array (‘index‘ => $this->result, ‘count‘ => $this->c_count );

        $this->commentIndex->update ( array ("_id" => $id ), array (‘$set‘ => $set ) );
        // 更新完成销毁变量
        $this->deletelist = $this->result = array ();
    }
}
php 操作mongodb

 

这里进行说明一下

    /**
     * 数据库初始化,正式项目在配置文件中生成
     * @mongodb
     */
    public function mongoInit() {
        try {
            $this->conn = new MongoClient ( "mongodb://php:123456@127.0.0.1:27017/comment");  这里连接方式是授权方式 数据库是comment
            $this->collection = $this->conn->selectCollection ( "comment", "comment");  //数据库comment   集合相当于表 comment
            $this->commentIndex = $this->conn->selectCollection ("comment", "commentIndex");  //数据库comment   集合相当于表 commentIndex
        } catch ( MongoConnectionException $e ) {
            exit ( ‘<p>Couldn\‘t connect to mongodb, is the "mongo" process running?</p>‘ );
        }
    }

//链接方法有很多如:

//*************************
//**   连接MongoDB数据库  **//
//*************************
//格式=>(“mongodb://用户名:密码 @地址:端口/默认指定数据库”,参数)
$conn = new Mongo();
//可以简写为
//$conn=new Mongo(); #连接本地主机,默认端口.
//$conn=new Mongo(“172.21.15.69″); #连接远程主机
//$conn=new Mongo(“xiaocai.loc:10086″); #连接指定端口远程主机
//$conn=new Mongo(“xiaocai.loc”,array(“replicaSet”=>true)); #负载均衡
//$conn=new Mongo(“xiaocai.loc”,array(“persist”=>”t”)); #持久连接
//$conn=new Mongo(“mongodb://sa:123@localhost”); #带用户名密码
//$conn=new Mongo(“mongodb://localhost:27017,localhost:27018″); #连接多个服务器
//$conn=new Mongo(“mongodb:///tmp/mongo-27017.sock”); #域套接字
//$conn=new Mongo(“mongodb://admin_miss:miss@localhost:27017/test”,array(‘persist’=>’p‘,”replicaSet”=>true)); #完整

这里是初始化mongodb

接下来就是操作了

     插入comment数据:

            $postData = array (
                    ‘id‘ => 1,
                    ‘author‘ => ‘作者‘,
                    ‘comment‘ => ‘内容‘,
                    ‘date‘ => new MongoTimestamp (), //插入时间 这个是mongo的类
                    ‘type‘ => ‘blog‘,  //类型
            );

  $this->comment->insert ( $postData);

-----------------------------------------------------------------------------------

  查询所有数据:

  $result = $this -> comment -> find();

  这里获取$result 是mongo结果集   不是二维数组

  foreach($result as $k => $v){

    var_dump($v);  //打印数据

  }

 ---------------------------------------------------------------------------------

  查询数据带条件

  $query = array(‘type‘ => ‘blog‘, ‘id‘ => 1);  //查询 type 为blog的 并且id为1的

  $result = $this -> comment -> find($query);

  这里获取$result 是mongo结果集   不是二维数组

  foreach($result as $k => $v){

    var_dump($v);  //打印数据

  }

---------------------------------------------------------------------------------------------

  查询数据带条件 分页

  $query = array(‘type‘ => ‘blog‘, ‘id‘ => 1);  //查询 type 为blog的 并且id为1的

  $result = $this -> comment -> find($query) ->limit ( 最大页码数 ) -> skip(跳过的页数);   这里是取出前十条记录   skip是跳过多少行  limit是取出多少

  跳过的页数 = (当前页数 -1)* 最大页码数    

  这里获取$result 是mongo结果集   不是二维数组

  foreach($result as $k => $v){

    var_dump($v);  //打印数据

  }

----------------------------------------------------------------------------------------------------

  查询数据带条件 分页 排序

  $query = array(‘type‘ => ‘blog‘, ‘id‘ => 1);  //查询 type 为blog的 并且id为1的

  $result = $this -> comment -> find($query) ->limit ( 最大页码数 ) -> skip(跳过的页数)-> sort(array(‘_id‘ => -1));   //这里_id是mongo自动生成的 

  1正序   -1 倒序 

  这里是取出前十条记录   skip是跳过多少行  limit是取出多少

  跳过的页数 = (当前页数 -1)* 最大页码数    

  这里获取$result 是mongo结果集   不是二维数组

  foreach($result as $k => $v){

    var_dump($v);  //打印数据

  }

  ------------------------------------------------------------------------------------------------------------------

  取出一个表的总数

  $count= $this -> comment ->count(); 

  echo $count;

  ------------------------------------------------------------------------------------------------------------------

  取出一个表的总数 带条件

  $query = array(‘id‘ => 1);

  $count= $this -> comment ->find($query) -> count(); 

  echo $count;

-----------------------------------------------------------------------------------------------------------------------------------

  查询一条数据

  $id = ‘mongoid‘;

  $query = array(‘_id‘ => ( object ) new MongoId($id));

  $findOne= $this -> comment ->findOne($query);

---------------------------------------------------------------------------------------------------------------------------------

  删除数据

  $id = ‘mongoid‘;

  $query = array(‘_id‘ => ( object ) new MongoId($id));

  $findOne= $this -> comment ->remove($query);

---------------------------------------------------------------------------------------------------------------------------------

  修改数据

    $id = ‘mongoid‘;

        $where = array(‘_id‘ => ( object ) new MongoId($id));
        $updateData  = array(‘$set‘ => array(‘comment‘ => ‘修改内容‘));
        $result = $this -> collection -> update($where, $updateData);

   return $result[‘updatedExisting‘];  成功返回 true  失败 false

 

php 操作mongodb,布布扣,bubuko.com

php 操作mongodb

上一篇:Oracle Enterprise Manager打不开的解决方法


下一篇:sqlserver的分页语句