高效mongodb的php分页类(不使用skip)

//$conn=new Mongo(); #连接本地主机,默认端口.

  *

  *
  * Lists all indexes in a collection.
  *
  * @usage = $this->mongo_db->list_indexes($collection);
  */
 public function list_indexes($collection = “”) {
  if(empty($collection))
  {
    show_error(“No Mongo collection specified to remove all indexes
from”, 500);
   }
   return($this->db->{$collection}->getIndexInfo());
 }

 /**

//*************************

  *

  * 获取表名

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

  *

  *  参数:
  *  $last 定位当前页的值
  *  $size 页面大小
  */
 public function get_prev($last, $size = PAGE_SIZE){
  if($last){
   if($this->page_sorts[$this->key] == 1){
   
$this->where_lt($this->key,$last)->order_by(array($this->key
=> -1));
   } else {
   
$this->where_gt($this->key,$last)->order_by(array($this->key
=> 1));
   }
   $result = $this->limit($size)->get($this->collection);
  }
  return $result[$size – 1][$this->key];
 }

  /**

  }

  *

  *  参数:
  *  $table 表名
  */
 public function set_table($table){
  $this->collection = $table;
 }

 /**


  *

  *
  * Get the documents where the value of a $field is less than or equal
to $x
  *
  * @usage = $this->mongo_db->where_lte(‘foo’, 20);
  */

  public function where_lte($field = “”, $x)
  {
   $this->where_init($field);
   $this->wheres[$field][‘$lte’] = $x;
   return($this);
  }

 /**

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

  *

  *
  * Offset the result set to skip $x number of documents
  *
  * @usage = $this->mongo_db->offset($x);
  */

  public function offset($x = 0)
  {
   if($x !== NULL && is_numeric($x) && $x >= 1)
   {
    $this->offset = (int) $x;
   }
   return($this);
  }

 /**

//$conn=new Mongo(“xiaocai.loc”,array(“replicaSet”=>true)); #负载均衡

 private $CI;
 private $config_file = ‘MongoDB’;

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

  *

  *
  * Determine which fields to include OR which to exclude during the
query process.
  * Currently, including and excluding at the same time is not
available, so the
  * $includes array will take precedence over the $excludes array.  If
you want to
  * only choose fields to exclude, leave $includes an empty array().
  *
  * @usage: $this->mongo_db->select(array(‘foo’,
‘bar’))->get(‘foobar’);
  */

 public function select($includes = array(), $excludes = array())
 {
   if(!is_array($includes))
   {
    $includes = array();
   }

   if(!is_array($excludes))
   {
    $excludes = array();
   }

   if(!empty($includes))
   {
    foreach($includes as $col)
    {
     $this->selects[$col] = 1;
    }
   }
   else
   {
    foreach($excludes as $col)
    {
     $this->selects[$col] = 0;
    }
   }
   return($this);
 }

 /**

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

如果能够通过查询条件查出每页结果的最后一条记录,在用最后一条记录作为查询条件去查下一页,这样每次都查询页面size条记录,效率不会差。

 

  *

  * 求反

接下来就是操作了

  *

  *  参数:
  *  $last 定位当前页的值
  *  $size 页面大小
  */
 public function page_query($last, $size = PAGE_SIZE){
  if($last){
   if($this->page_sorts[$this->key]==1){
    $this->where_gte($this->key,$last);
   } else {
    $this->where_lte($this->key,$last);
   }
  }
  return
$this->limit($size)->order_by($this->page_sorts)->get($this->collection);
 }

 /**
  * 批量执行代码_插入
  * @param String $collection
  * @param 二维数组 $code
  */
 public function execute_insert($collection,$code){
  //将二维数组分成js格式
  $strcode=”;
  foreach($code as $k=>$v){
   foreach($v as $kk=>$vv){
    $strcode.=’db.getCollection(“‘.$collection.'”).insert({
“‘.$kk.'”:”‘.$vv.'” });’;
   }   
  }
 // retrun array([ok]=>1);
  return $this->db->execute($code); 
 }

}
?>

page.class.php mongodb分页逻辑类

复制代码 代码如下:

<?php
db = $DB;
  $this->count =
$this->db->count($this->db->get_table());
  $url = SITE_ROOT.strtolower(CLASS_NAME).’/’.METHOD_NAME;
  $this->url = $this->url ? $this->url : $url;
  $set = $set ? $set : 5;
  $this->set = $set;
  $size = $size ? $size : PAGE_SIZE;
  $this->size = $size;
  $this->last = $last;
  $this->prev = $DB->get_prev($this->last);
  $this->next = $DB->get_next($this->last);
  //$this->page = GET::UINT(‘page’);
  $this->page = $this->page ? $this->page : 1;
  $this->total = @ceil($this->count / $this->size);
  $this->key = $key;
  $this->orderby = $orderby;
 }

 //输出分页链接
 public function get_link(){
  if($this->total != 1){
   $this->get_first();
   $this->get_prev();
   $this->get_center();
   $this->get_next();
   $this->get_last();
   $this->get_turnto();
  }
  if($this->link){
   $this->link =
$this->turnto.$this->link.’共’.number_format($this->total).’页
‘.number_format($this->count).’条记录’;
  }
  if($this->turnto){
   $this->link .= ”;
  }
  return $this->link;
 }

 //获取左边显示的个数
 public function get_left(){
  return  $this->left = ($this->set – $this->page >= 0) ?
($this->page – 1) : $this->set;
 }

 //获取右边显示的个数
 public function get_right(){
  return $this->right = ($this->total – $this->page >
$this->set) ? $this->set : ($this->total – $this->page);
 }

 //设置左边的结果集
 public function set_left_result($left_result){
  $this->leftresult = $left_result;
 }

 //设置右边的结果集
 public function set_right_result($right_result){
  $this->rightresult = $right_result;
 }

 //设置排序条件
 public function set_orderby($orderby){
  $this->orderby = $orderby;
 }

 //设置最后一页
 public function set_last($last){
  $this->lastd = $last;
 }

 //设置中间显示页码个数
 public function set($set){
  $this->set = $set;
 }

 //获取首页
 private function get_first(){
  if($this->page != 1){
   if($this->total > 0){
    $this->link.=’首页’;
   }
  }
 }

 //获取上一页
 private function get_prev(){
  if($this->prev){
   $this->link.=’上一页’;
  }
 }

 //中间显示
 private function get_center(){
  $start = ($this->page – $this->set) <= 0 ? 1 :
($this->page – $this->set); 
  $end = ($this->page + $this->set + 1 >= $this->total) ?
$this->total + 1 : ($this->page + $this->set + 1);

  $ii = $this->left;
  $iii = 0;
  //显示左边的
  for($i = $start; $i < $end; $i++, $ii–, $iii++){
   if($this->page == $i){
    $this->link.=”.$i.”;
   }else{
    $the_id = $ii * $this->size – 1;
    if($the_id > 0){
     $this->link.=”.$i.”;
    }else{
     $the_id = ($iii – $this->left) * $this->size;
     $this->link.=”.$i.”;
    }   
   }
  }
 }

 //获取下一页
 private function get_next(){
  if($this->next){
   $this->link.=’下一页’;
  }
 }

 //获取尾页
 private function get_last(){
  if($this->page != $this->total){
   $this->link.=’尾页’;
  }
 }

 //跳转到
 private function get_turnto(){
  $this->turnto = ‘
转到第 <input type=”text” name=”p”
style=”width:25px;text-align:center”> 页’;
 }

 //求反
 public function nor_orderby(){
  foreach($this->orderby as $key => $order){
   if($order==-1){
    $orderby[$key] = 1;
   }else{
    $orderby[$key] = -1;
   }  
  }
  return $orderby;
 }

 //设置key
 public function set_key($key){
  $this->key = $key;
 }

 //分页操作
 public function show(){
  $this->set_key($this->key);
  $this->set_orderby($this->orderby);
  $left = $this->get_left();
  $right = $this->get_right();
  $leftresult = $this->db->get_left($left, $this->last);
  $rightresult = $this->db->get_right($right, $this->last);
  $this->set_left_result($leftresult);
  $this->set_right_result($rightresult);
  $last = $this->db->get_last();
  $this->set_last($last);
  return $this->get_link();
 }
}
/*      调用例子rockmongo
  global $DB;
  $lastid = GET::UINT(‘id’);
  $table = ‘log’;
  $key = ‘_id’;
  $orderby = array($key => -1);

  $DB->set_table($table);
  $DB->set_key($key);
  $DB->set_orderby($orderby);

  $log = $DB->page_query($lastid);

  $page = new Page($lastid, $key, $orderby);
  $pager = $page->show();
*/

?>

test.php 测试代码

复制代码 代码如下:

<?php
  include “page.class.php”;
  include “mongodb.class.php”;
  define(PAGE_SIZE, 5);//每页大小
  $config[‘HOST’] = ‘127.0.0.1’;
  $config[‘PORT’] = 20081;  //mongodb端口
  $config[‘DATABASE’] = ‘domain’;//mongodb数据库名
  $config[‘USER’] = ”;
  $config[‘PWD’] = ”;
  $config[‘PERSIST’] = TRUE;

  $DB = new DB($config);

  $table = ‘whois’; //mongodb collection名
  $key = ‘_id’;
  $orderby = array($key => -1);

  $DB->set_table($table);
  $DB->set_key($key);
  $DB->set_orderby($orderby);

  $log = $DB->page_query($lastid,5);

  $page = new Page($lastid, $key, $orderby);

  echo $pager = $page->show();

?>

    $id = ‘mongoid’;

  *

  * WHERE LESS THAN OR EQUAL TO PARAMETERS

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

  *

  * LIKE PARAMETERS

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

  *

  *
  * Limit the result set to $x number of documents
  *
  * @usage = $this->mongo_db->limit($x);
  */

  public function limit($x = 99999) {
   if($x !== NULL && is_numeric($x) && $x >= 1)
   {
    $this->limit = (int) $x;
   }
   return($this);
  }

 /**

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

  *

  *
  * Remove an index of the keys in a collection. To set values to
descending order,
  * you must pass values of either -1, FALSE, ‘desc’, or ‘DESC’, else
they will be
  * set to 1 (ASC).
  *
  * @usage = $this->mongo_db->remove_index($collection,
array(‘first_name’ => ‘ASC’, ‘last_name’ => -1));
  */

 public function remove_index($collection = “”, $keys = array())
 {
  if(empty($collection))
  {
    show_error(“No Mongo collection specified to remove index from”,
500);
   }

   if(empty($keys) || !is_array($keys))
   {
    show_error(“Index could not be removed from MongoDB Collection
because no keys were specified”, 500);
   }

   if($this->db->{$collection}->deleteIndex($keys, $options) ==
TRUE)
   {
    $this->clear();
    return($this);
   }
   else
   {
    show_error(“An error occured when trying to remove an index from
MongoDB Collection”, 500);
  }
 }

 /**

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

  *

  *
  * Switch from default database to a different db
  */

 public function switch_db($database = ”)
 {
  if(empty($database))
  {
   show_error(“To switch MongoDB databases, a new database name must be
specified”, 500);
  }
  $this->dbname = $database;
  try
  {
   $this->db = $this->connection->{$this->dbname};
   return(TRUE);
  }
  catch(Exception $e)
  {
   show_error(“Unable to switch Mongo Databases:
{$e->getMessage()}”, 500);
  }
 }

 /**

  删除数据

  *

  * 分页查询

//$conn=new Mongo(“xiaocai.loc:10086″); #连接指定端口远程主机

  *

  * BUILD CONNECTION STRING

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

  *

  *
  * Insert a new document into the passed collection
  *
  * @usage = $this->mongo_db->update_all(‘foo’, $data =
array());
  */

  public function update_all($collection = “”, $data = array()) {
   if(empty($collection))
   {
    show_error(“No Mongo collection selected to update”, 500);
   }

   if(count($data) == 0 || !is_array($data))
   {
    show_error(“Nothing to update in Mongo collection or update is not
an array”, 500);
   }

   try
   {
    $this->db->{$collection}->update($this->wheres,
array(‘$set’ => $data), array(‘fsync’ => TRUE, ‘multiple’ =>
TRUE));
   $this->clear();
    return(TRUE);
   }
   catch(MongoCursorException $e)
   {
    show_error(“Update of data into MongoDB failed:
{$e->getMessage()}”, 500);
   }

  }

  /**

//$conn=new Mongo(“172.21.15.69″); #连接远程主机

  *

  *
  * Get the documents based on these search parameters.  The $wheres
array should
  * be an associative array with the field as the key and the value as
the search
  * criteria.
  *
  * @usage = $this->mongo_db->where(array(‘foo’ =>
‘bar’))->get(‘foobar’);
  */

  public function where($wheres = array())
  {
   foreach($wheres as $wh => $val)
   {
    $this->wheres[$wh] = $val;
   }
   return($this);
  }

 /**

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

mongodb.class.php mongodb 操作类

  }

  *

  *
  * Get the documents based upon the passed parameters
  *
  * @usage = $this->mongo_db->get(‘foo’, array(‘bar’ =>
‘something’));
  */

  public function get($collection = “”)
  {
   if(empty($collection))
   {
    show_error(“In order to retreive documents from MongoDB, a
collection name must be passed”, 500);
   }
   $results = array();
   $documents =
$this->db->{$collection}->find($this->wheres,
$this->selects)->limit((int) $this->limit)->skip((int)
$this->offset)->sort($this->sorts);

   $returns = array();

   foreach($documents as $doc):
    $returns[] = $doc;
   endforeach;
  $this->clear();
   return($returns);

  }

 /**

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

  *

  *  参数:
  *  $key 设置索引主键
  */
 public function set_key($key){
  $this->key = $key;
 }

 /**

这里是初始化mongodb

  *

  * COUNT

//$conn=new Mongo(“xiaocai.loc”,array(“persist”=>”t”)); #持久连接

  *

  *  参数:
  *  $orderby 排序
  */
 public function set_orderby($orderby){
  $this->page_sorts = $orderby;
 }

 
 /**

  查询数据带条件 分页

  *

  *
  * Removes the specified collection from the database.  Be careful
because this
  *  can have some very large issues in production!
  */

  public function drop_collection($collection = “”)
  {
    if(empty($collection))
   {
      show_error(“No Mongo collection specified to drop from database”,
500);
    }
    $this->db->{$collection}->drop();
    return TRUE;
  }

 /**

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

  *

  * LIMIT DOCUMENTS

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

  *

  */
 private function nor_orderby(){
  foreach($this->page_sorts as $key => $order){
   if($order == -1){
    $orderby[$key] = 1;
   }else{
    $orderby[$key] = -1;
   }  
  }
  return $orderby;
 }

 /**

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

 private $selects = array();
 private $wheres = array();
 private $sorts = array();
 private $page_sorts = array();


  *

  * WHERE LESS THAN PARAMETERS

  $id = ‘mongoid’;

  *

  *  参数:
  *  $right 右边显示的个数
  *  $last 定位当前页的值
  *  $size 页面大小
  */
 public function get_right($right, $last, $size = PAGE_SIZE){
  if($last){
   if($this->page_sorts[$this->key] == -1){
    $this->where_lte($this->key, $last);
   } else {
    $this->where_gte($this->key, $last);
   }
  }
  return $this->limit($right * $size +
1)->order_by($this->page_sorts)->get($this->collection);
 }

 /**

  取出一个表的总数 带条件

  *

  * LIST_INDEXES

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

  *

  *  参数:
  *  $size 页面大小
  */
 public function get_last($size = PAGE_SIZE){
  $res = $this->count($this->collection) % $size;
  $order = $this->nor_orderby();
  if($res > 0){
   $result =
$this->limit($res)->order_by($order)->get($this->collection);
   return $result[$res – 1][$this->key];
  }else{
   $result =
$this->limit($size)->order_by($order)->get($this->collection);
   return $result[$size – 1][$this->key];
  }
 }

 /**

图片 1

  *

  * CLEAR

  

<?php
function show_error($message, $status_code = 500, $heading = ‘An Error
Was Encountered’)
{
        echo $message, $status_code,PHP_EOL;
        exit;
}

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

  *

  *
  * Remove all indexes from a collection.
  *
  * @usage = $this->mongo_db->remove_all_index($collection);
  */

 public function remove_all_indexes($collection = “”) {
  if(empty($collection))
  {
    show_error(“No Mongo collection specified to remove all indexes
from”, 500);
   }

   $this->db->{$collection}->deleteIndexes();
   $this->clear();
   return($this);
 }

 /**

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

  *

  *
  * Count the documents based upon the passed parameters
  *
  * @usage = $this->mongo_db->get(‘foo’);
  */

  public function count($collection = “”)
  {
   if(empty($collection))
   {
    show_error(“In order to retreive a count of documents from MongoDB,
a collection name must be passed”, 500);
   }
   $count =
$this->db->{$collection}->find($this->wheres)->limit((int)
$this->limit)->skip((int) $this->offset)->count();
   $this->clear();
   return($count);
  }

 /**
  * 自增ID实现
  * return insert_id
  */
 private function insert_inc($table)
 {
  $update = array(‘$inc’=>array(‘id’=>1));
  $query = array(‘table’=>$table);
  $command = array(
  ‘findandmodify’=>’_increase’,
  ‘update’=>$update,
  ‘query’=>$query,
  ‘new’=>true,
  ‘upsert’=>true
  );
  $id = $this->db->command($command);
  return $id[‘value’][‘id’];
 }

 /**


 /**

//**   连接MongoDB数据库  **//

mongodb分页skip+limit分页要先查出所有结果再去跳过,这样如果查询页面越往后效率越低。

     插入comment数据:

  *

  * Switch_db

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

  *

  *
  * Establish a connection to MongoDB using the connection string
generated in
  * the connection_string() method.  If ‘mongo_persist_key’ was set
to true in the
  * config file, establish a persistent connection.  We allow for only
the ‘persist’
  * option to be set because we want to establish a connection
immediately.
  */

 private function connect() {
  $options = array();
  if($this->persist === TRUE)
  {
   $options[‘persist’] = isset($this->persist_key) &&
!empty($this->persist_key) ? $this->persist_key :
‘ci_mongo_persist’;
  }

  try
  {
   $this->connection = new Mongo($this->connection_string,
$options);
   $this->db = $this->connection->{$this->dbname};
   return($this);
  }
  catch(MongoConnectionException $e)
  {
   show_error(“Unable to connect to MongoDB: {$e->getMessage()}”,
500);
  }
 }

 /**

 ———————————————————————————

  *

  * 获取右边结果集

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

  *

  * DELETE

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

  *

  * 设置表

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

  *

  *  参数:
  *  $last 定位当前页的值
  *  $size 页面大小
  */
 public function get_next($last, $size = PAGE_SIZE){
  if($last){
   if($this->page_sorts[$this->key] == 1){
    $this->where_gte($this->key,$last);
   } else {
    $this->where_lte($this->key,$last);
   }
  }
  $result =
$this->limit($size+1)->order_by($this->page_sorts)->get($this->collection);
  return $result[$size][$this->key];
 }

 /**

//$conn=new Mongo(“mongodb:///tmp/mongo-27017.sock”); #域套接字

  *

  *
  * Prepares parameters for insertion in $wheres array().
  */

 private function where_init($param)
 {
  if(!isset($this->wheres[$param]))
  {
   $this->wheres[$param] = array();
   }
 }

 /**

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

  *

  * 设置表排序

  echo $count;

  *

  * ORDER BY PARAMETERS

<?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  >'.$tip.'</font></p>';                  break;              case 'blue':                  $str = '<p>'.$word.'<font  >'.$tip.'</font></p>';                  break;              default:                  $str = '<p>'.$word.'<font  >'.$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 ();      }  }

 *

 * Where size

  修改数据

复制代码 代码如下:


  *

  * WHERE GREATER THAN OR EQUAL TO PARAMETERS

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

  *

  * WHERE OR

  }

  *

  *
  * Get the documents where the value of a $field is in a given $in
array().
  *
  * @usage = $this->mongo_db->where_in(‘foo’, array(‘bar’,
‘zoo’, ‘blah’))->get(‘foobar’);
  */

  public function where_in($field = “”, $in = array())
  {
   $this->where_init($field);
   $this->wheres[$field][‘$in’] = $in;
   return($this);
  }

 /**

//链接方法有很多如:

  *

  *
  * Ensure an index of the keys in a collection with optional
parameters. To set values to descending order,
  * you must pass values of either -1, FALSE, ‘desc’, or ‘DESC’, else
they will be
  * set to 1 (ASC).
  *
  * @usage = $this->mongo_db->add_index($collection,
array(‘first_name’ => ‘ASC’, ‘last_name’ => -1), array(‘unique’
=> TRUE));
  */

 public function add_index($collection = “”, $keys = array(), $options
= array())
 {
  if(empty($collection))
  {
    show_error(“No Mongo collection specified to add index to”, 500);
   }

   if(empty($keys) || !is_array($keys))
   {
    show_error(“Index could not be created to MongoDB Collection
because no keys were specified”, 500);
    }

   foreach($keys as $col => $val)
   {
    if($val == -1 || $val === FALSE || strtolower($val) == ‘desc’)
    {
     $keys[$col] = -1;
    }
    else
    {
     $keys[$col] = 1;
    }
   }

   if($this->db->{$collection}->ensureIndex($keys, $options) ==
TRUE)
   {
    $this->clear();
    return($this);
   }
   else
   {
    show_error(“An error occured when trying to add an index to MongoDB
Collection”, 500);
  }
 }

 

 /**

//$conn=new Mongo(“mongodb://sa:123@localhost”); #带用户名密码

  *

  * REMOVE_INDEX

  ——————————————————————————————————————

 private $collection = ”;
 private $host;
 private $port;
 private $user;
 private $pass;
 private $dbname;
 private $key;
 private $persist;
 private $persist_key;

相关文章