MongoDB Operation class PHP code

Source: Internet
Author: User

<?phpinclude_once dirname (DirName (dirname (__file__))). Directory_separator. ' Config '. Directory_separator. ' database.php ';class mongoclass3{  static public  $conn;//Database connection   static  public  $db;//Database Selection   static public  $collection;//result set   public  $debug;   public function __construct ($type =0) {     $database = ';      $database  = new database_config ()     if ($type ==1) {          $mongo _master =  $database->mongo_hems3;     }else if ($type ==2)  {        $mongo _master = $ Database->mongo162;    }else if ($type  == 3)  {           $mongo _master =  $database->mongo_yuanchuang;     } else iF ($type ==5)  {         $mongo _master =  $database Mongo_backup;    }    else if ($type  == 0) {          $mongo _master =  $database->mongo;    }      $host _master =  $mongo _master[' host '];     $database      =  $mongo _master[' database '];     $port          =  $mongo _master[' Port '];     $this->debug = true;//      $this->conn = new mongo ("Mongodb://${username}:${password}@${host}") ;//     $this->conn = new mongo ("Mongodb://${host_master},${host_slave}", Array ("Replicaset"  =>  "Shard"));    try{          $this->cOnn = new mongo ("Mongodb://${host_master}:${port}");     }catch (Exception   $e) {         $str  =  $e. " \ r \ n ". Date (' Y-m-d h:i:s ', Time ())."   Connection MONGO failed \ r \ n ";         $this->getmongologo ($STR);         return false;    }//       $this->conn= $db->admin;//      $this->conn->authenticate (' root ',   ' 123456 ');     $this->db =  $this->conn->{$database};  }     /**     * Description  Query Configuration Table Hems_basic Record Count   Records can be queried by criteria      *  @param  Array  $conditions    Nullable    The conditional format is an array of   array (' field 1 ' = = ' field value 1 ', ' field 2 ' = ' = ' field value 2 ')   indicates that the condition is an and relationship      *   @return &NBSP;INT&NBsp;  $count      *     */    public  function getcount ($collection, $conditions  = array ()) {          $this->collection =  $this->db->{$collection};          $count  =  $this->collection->find ($conditions)->count ();         return  $count;    }    /**      * Description  Query Configuration table Hems_basic document based on condition      * @ param  array  $conditions    Nullable      conditional format for an array   array (' field 1 ' = > ' field value 1 ', ' field 2 ' = = ' field value 2 ')   indicates that the condition is between and relationship      *  @return  array $ res   returns the result that the MONGO object needs to traverse to fetch the data      *     */     public&nbsP;function getdata ($collection, $conditions  = array (), $field =array (), $order =array (), $start =0,$ PERNUM=20) {         $this->collection =  $this->db->{ $collection};        if (Empty ($collection)) {             return false;         }        try {             if ($start ==1&& $pernum ==0) {                 if ($order) {                      $res  =  $this Collection->find ($conditions, $field)->slaveokay (True)->sort ($order);                 }else{                      $res  =  $this->collection->find ($conditions, $ field)->slaveokay (true);                 }            }else{                 if ($order) {                     $ res =  $this->collection->find ($conditions, $field)->slaveokay (True)->sort ($order) Skip ($start)->limit ($pernum);                 }else{                      $res  =  $this->collection->find ($conditions, $field)->slaveokay (True)->skip ($ Start)->limit ($pernum);                 }            }         }catch (exception  $e) {              $res  = array ();             $ Str =  date (' Y-m-d h:i:s ', Time ()). "   from collection ". $collection." Get data \ r \ n conditions are: \ r \ n ";             $str 1= ";             foreach ($conditions  as  $key  =>  $val) {                  $str 1.=  $key. " ------------". $val." \r\N ";            }              $this->getmongologo ($str. $str 1. " Failure \ r \ n ");            return false;         }        try{              $res->rewind ();         }catch (exception  $e) {              $str  =  date (' Y-m-d h:i:s ', Time ()). "   from collection ". $collection." Get data \ r \ n conditions are: \ r \ n ";             $str 1= ";             foreach ($conditions  as  $key  =>  $val) {                 $str 1.=  $key. " ------------". $val." \ r \ n ";            }              $this->getmongologo ($str. $str 1. " Failure \ r \ n ");            return false;         }        if ($res->valid () ) {            return iterator_to_array ($res, True);        }else{             return false;        }     }    /**     * Description  Query Configuration table Hems_basic documents based on conditions      *  @param   Array  $conditions    can be empty      conditional format is an array of   array (' field 1 ' = = ' field value 1 ', ' field 2 ' = ' = ' field value 2 ')   indicates that the condition is between and relationship       *  @return  Array  $res    Returns the result that the MONGO object needs to traverse to fetch the data       *     */    public function getdataor ($collection, $conditions) {         $this->collection =  $this->db->{$ collection};         $res  =  $this->collection->find ( Array (' $or ' = $conditions));        return  $res;     }    /**     * Description  Calculates the number of all documents in a datasheet (calculated by criteria, the total number of entire collections is evaluated unconditionally)      *  @param  Array  $conditions   Nullable      Conditional format array   array (' field 1 ' = ' = ' field value 1 ', ' field 2 ' = ' = ' field value 2 ')   indicates that the condition is between and relationship       *&nbsp, @return  int   $count      */    public  Function getiddatacount ($collection, $conditions  = array ()) {          $this->collection =  $this->db->{$collection};          $count  =  $this->collection->find ($conditions)->count ();         return  $count;    }    /**      * Description  Remove all document documents according to the criteria or _id in the configuration table to the Hems_data data sheet       *  @param  Array  $conditions   Nullable     conditional format array   array (' field 1 ' = = ' Field value 1 ', ' field 2 ' = = ' field value 2 ')   indicates that the condition is between and relationship      *  @return  Array  $res    returns the result that the MONGO object needs to traverse to fetch the data      */    public  Function getiddata ($collection, $conditions) {         $this->collection =  $this db->{$collection};         $res  =  $this->collection- >find ($conditions);        return  $res;     }    /**     * Description  Modify data table documents according to conditions       *  @param  Array  $conditions   $data     $conditions formats for arrays   array (' field 1 ' = ' = ' field value 1 ', ' field 2 ' = ' = ' field value 2 ')   indicates multiple conditions side by side      *                                     $data formats for arrays    Array (' field 1 ' = = ' field value 1 ', ' field 2 ' = ' = ' field value 2 ')   indicates modified field      */     Public function editdaTa ($collection, $conditions, $data) {         $this->collection =   $this->db->{$collection};        if ($this->collection- >update ($conditions  ,array (' $set ' = + $data), array (' multiple ' =>1)) {              $code  = 1;              $msg   =  ' modified successfully! ';         }else{              $code  = 0;             $msg   =  ' modification failed! ';         }        return  Array (' Code ' = $code, ' msg ' = + $msg);    }         /*     * D escription  Delete Data sheet documents based on criteria      *  @param  Array  $conditions       $conditions Format Array   array (' field 1 ' = = ' field value 1 ', ' field 2 ' = ' = ' field value 2 ')   represents multiple conditions side by side       */    public function deldata ($collection, $conditions) {          $this->collection =  $this->db->{$collection };        if ($this->collection->remove ($conditions)) {              $code  = 1;              $msg   =  ' delete succeeded! ';         }else{              $code  = 0;             $msg   =  ' delete failed! ';     &nBsp;   }        return array (' Code ' = $code, ' msg ' = $msg);    }    /*     * description   Insert Operation      *  Judging by primary key _id, if the record already exists      */     public function save ($collection, $field, $flag =0) {          $this->collection =  $this->db->{$collection};          $log  =  "";         foreach ($field  as  $kdata  =>  $vdata) {              $log  .=  $kdata. ":". $vdata. ",";        }          $log  = trim ($log, ",");          $newLog  =  "\r\n-------\r\ntime: ". Date (" Y-m-d h:i:s ")." \r\ndata ". $log;         $oldLog  = file_get_contents (".. /tmp/mongolog.txt ");         @file_put_contents (".. /tmp/mongolog.txt ", $oldLog. $newLog);         if ($flag) {            $result  =  $this->collection->save ($field, array (' safe ' =>1);         }else{            $result  =  $this->collection->insert ($field, Array (' safe ' =>1));         }        return  $result;     }   }?>

This article is from the "PHP Program ape" blog, please be sure to keep this source http://okowo.blog.51cto.com/4923464/1690710

MongoDB Operation class PHP code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.