PHP MongoDB Operation class with a few simple examples

Source: Internet
Author: User
Tags findone php mongodb
Before the script house has sent a few similar articles, we can refer to.

Core code:

Class Newmongodb {private $mongo;  Newmongodb connection Private $curr _db_name;  Private $curr _table_name;  Private $error;  public $config;    Public Function getinstance ($mongo _server, $flag =array ()) {static $NewMongodb _arr;     if (Empty ($flag [' tag ')]) {$flag [' tag '] = ' default ';      if (Isset ($flag [' Force ']) && $flag [' force '] = = true) {$mongo = new Newmongodb ($mongo _server);      if (Empty ($NewMongodb _arr[$flag [' tag ']]) {$NewMongodb _arr[$flag [' tag ']] = $mongo;    } return $mongo;  } else if (Isset ($NewMongodb _arr[$flag [' tag ']) && is_resource ($NewMongodb _arr[$flag [' tag '])) {return    $NewMongodb _arr[$flag [' tag '];      } else {$mongo = new Newmongodb ($mongo _server);      $NewMongodb _arr[$flag [' tag '] = $mongo;    return $mongo; }}/** * constructor * supports incoming multiple mongo_server (1. A problem when connecting to other servers 2. Automatically distribute queries evenly to different servers) * Parameters: * $mongo _server: Array or string-a Rray ("127.0.0.1:1111", "127.0.0.1:2222")-"127.0.0.1:1111 "* $connect: Whether to initialize MONGO object when connected, default connection * $auto _balance: Whether to do load balancing automatically, default is * * * return Value: * Success: MONGO Object * failed: false   */Public Function __construct ($mongo _server, $connect =true, $auto _balance=true) {if (Is_array ($mongo _server)) {   $mongo _server_num = count ($mongo _server);    if ($mongo _server_num > 1 && $auto _balance) {$prior _server_num = rand (1, $mongo _server_num);    $rand _keys = Array_rand ($mongo _server, $mongo _server_num);    $mongo _server_str = $mongo _server[$prior _server_num-1]; foreach ($rand _keys as $key) {if ($key! = $prior _server_num-1) {$mongo _server_str. = ', '. $mongo _server[    $key];   }}}} else {$mongo _server_str = implode (', ', $mongo _server);   }} else {$mongo _server_str = $mongo _server;   try {$this->mongo = new Mongoclient ($mongo _server, Array (' connect ' = = $connect));    } catch (Mongoconnectionexception $e) {$this->error = $e->getmessage ();   return false;   }  }  /** * Connect NEWMONGODB Server * Parameter: None * * return Value: * Success: TRUE * Failed: false */Public function connect () {try {      $this->mongo->connect ();    return true;      } catch (Mongoconnectionexception $e) {$this->error = $e->getmessage ();    return false; }}/** * Select db * parameter: $dbname * * return value: none */Public Function Selectdb ($dbname) {$this->curr_db_name  = $dbname;  /** * Index is created: returns if the index already exists.  * Parameters: * $table _name: Table name * $index: Index-array ("id" =>1)-Ascending index in ID field * $index _param: Other criteria-whether unique index etc * * return value: * Success: TRUE * Failed: false */Public function ensureindex ($table _name, $index, $index _param=array ()) {$dbname = $this->curr_db_n    Ame    $index _param[' safe '] = 1;      try {$this->mongo-> $dbname, $table _name->ensureindex ($index, $index _param);    return true;      } catch (Mongocursorexception $e) {$this->error = $e->getmessage ();    return false; }}/** * Insert record * * parameter: * $table _name: Table name * $record: Record * * return value: * Success: TRUE * Failure: false */Public function Insert ($table _name, $record) {$dbname = $this-&G    T;curr_db_name;      try {$this->mongo-> $dbname, $table _name->insert ($record, Array (' safe ' =>true));    return true;      } catch (Mongocursorexception $e) {$this->error = $e->getmessage ();    return false;  }}/** * Number of records in query table * parameter: * $table _name: Table name * * Return value: Number of records in table */Public Function count ($table _name) {$dbname =    $this->curr_db_name;  Return $this->mongo-> $dbname, $table _name->count (); }/** * Update record * * Parameter: * $table _name: Table name * $condition: Update condition * $newdata: New data record * $options: Update selection-upsert/multiple * *  Return Value: * Success: TRUE * Failed: false */Public Function update ($table _name, $condition, $newdata, $options =array ()) {$dbname    = $this->curr_db_name;    $options [' safe '] = 1;     if (!isset ($options [' multiple '])) {$options [' multiple '] = 0; try {$this->mongo-> $dbnamE-> $table _name->update ($condition, $newdata, $options);    return true;      } catch (Mongocursorexception $e) {$this->error = $e->getmessage ();    return false; }}/** * Delete record * parameter: * $table _name: Table name * $condition: Delete condition * $options: Delete selection-justone * * return Value: * Success: TRUE * Failure: FA    LSE */Public Function remove ($table _name, $condition, $options =array ()) {$dbname = $this->curr_db_name;    $options [' safe '] = 1;      try {$this->mongo-> $dbname, $table _name->remove ($condition, $options);    return true;      } catch (Mongocursorexception $e) {$this->error = $e->getmessage ();  return false; }}/** * Find record * parameter: * $table _name: Table name * $query _condition: Field Find condition * $result _condition: Query Result Restrictions-limit/sort etc. * $f Ields: Get field * * return value: * Success: Recordset * failed: false */Public function find ($table _name, $query _condition, $result _condition=arr    Ay (), $fields =array ()) {$dbname = $this->curr_db_name; $cursor = $this->mongo-> $dbname $table _name->find ($query _condition, $fields);    if (!empty ($result _condition[' start ')) {$cursor->skip ($result _condition[' start ']);    } if (!empty ($result _condition[' limit ')) {$cursor->limit ($result _condition[' limit ');    } if (!empty ($result _condition[' sort ')) {$cursor->sort ($result _condition[' sort ']);    } $result = Array ();      try {while ($cursor->hasnext ()) {$result [] = $cursor->getnext ();      }} catch (Mongoconnectionexception $e) {$this->error = $e->getmessage ();    return false;      } catch (Mongocursortimeoutexception $e) {$this->error = $e->getmessage ();    return false;  } return $result; /** * Find a record * parameter: * $table _name: Table name * $condition: Find condition * $fields: Get field * * return value: * Success: One record * failed: false */P    ublic function FindOne ($table _name, $condition, $fields =array ()) {$dbname = $this->curr_db_name; Return $this->mongo-> $dbname $table _name->findone ($condition, $fields);  /** * Get current error message * parameter: None * * Return Value: Current error message */Public function GetError () {return $this->error;  }/*** Newmongodb Class * * Examples: * $mongo = new Newmongodb ("127.0.0.1:11223");  * $mongo->selectdb ("test_db");  * CREATE INDEX * $mongo->ensureindex ("test_table", Array ("id" =>1), Array (' unique ' =>true));  * Get records of the table * $mongo->count ("test_table");  * Insert Record * $mongo->insert ("test_table", Array ("id" =>2, "title" = "Asdqw"));  * Update record * $mongo->update ("test_table", Array ("id" =>1), Array ("id" =>1, "title" = "BBB")); * Update record-existing when updated, not present when adding-equivalent set * $mongo->update ("test_table", Array ("id" =>1), Array ("id" =>1, "title" = "BBB")  , Array ("Upsert" =>1)); * Find Records * $mongo->find ("C", Array ("title" = "Asdqw"), Array ("Start" =>2, "Limit" =>2, "Sort" =>array ("id" =  >1))) * Find a record * $mongo->findone ("$mongo->findone (" TTT ", Array (" id "=>1)", Array ("id" =>1)); * Delete Record *$mongo->remove ("TTT", Array ("title" = "BBB"));  * Delete Only one record * $mongo->remove ("TTT", Array ("title" = "BBB"), Array ("Justone" =>1));  * Get error message for MONGO operation * $mongo->geterror (); */}


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.