MongoDB database operations implemented by PHP _ php instance

Source: Internet
Author: User
Tags connect to mongodb server findone mongodb server
This article mainly introduces the MongoDB database operation class sharing implemented by PHP, and the operation class of the template mysql version. For more information, see The Code is as follows:


Class HMongodb {

Private $ mongo; // Mongodb connection
Private $ curr_db_name;
Private $ curr_table_name;
Private $ error;

Public function getInstance ($ pai_server, $ flag = array ())
{
Static $ mongodb_arr;
If (empty ($ flag ['tag'])
{
$ Flag ['tag'] = 'default ';}
If (isset ($ flag ['force']) & $ flag ['force'] = true)
{
$ Mongo = new HMongodb ($ mongo_server );
If (empty ($ mongodb_arr [$ flag ['tag'])
{
$ Mongodb_arr [$ flag ['tag'] = $ mongo;
}
Return $ mongo;
}
Else if (isset ($ mongodb_arr [$ flag ['tag']) & is_resource ($ mongodb_arr [$ flag ['tag'])
{
Return $ mongodb_arr [$ flag ['tag'];
}
Else
{
$ Mongo = new HMongodb ($ mongo_server );
$ Mongodb_arr [$ flag ['tag'] = $ mongo;
Return $ mongo;
}
}

/**
* Constructor
* Multiple mongo_servers can be input. (1. connect to other servers when a problem occurs. 2. Distribute queries evenly to different servers)
*
* Parameters:
* $ Pai_server: array or string-array ("127.0.0.1: 1111", "127.0.0.1: 2222")-"127.0.0.1: 1111"
* $ Connect: whether to connect to the mongo object during initialization. Default connection
* $ Auto_balance: whether to automatically perform load balancing. The default value is
*
* Return value:
* Success: mongo object
* Failed: false
*/
Private function _ construct ($ cmd_server, $ connect = true, $ auto_balance = true)
{
If (is_array ($ pai_server ))
{
$ Pai_server_num = count ($ pai_server );
If ($ pai_server_num> 1 & $ auto_balance)
{
$ Prior_server_num = rand (1, $ pai_server_num );
$ Rand_keys = array_rand ($ pai_server, $ pai_server_num );
$ Pai_server_str = $ pai_server [$ prior_server_num-1];
Foreach ($ rand_keys as $ key)
{
If ($ key! = $ Prior_server_num-1)
{
$ Pai_server_str. = ','. $ pai_server [$ key];
}
}
}
Else
{
$ Pai_server_str = implode (',', $ pai_server );
}}
Else
{
$ Pai_server_str = $ pai_server;
}
Try {
$ This-> mongo = new Mongo ($ mongo_server, array ('connect '=> $ connect ));
}
Catch (except connectionexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
}

/**
* Connect to mongodb server
*
* Parameter: None
*
* Return value:
* Success: true
* Failed: false
*/
Public function connect ()
{
Try {
$ This-> mongo-> connect ();
Return true;
}
Catch (except connectionexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
}

/**
* Select db
*
* Parameter: $ dbname
*
* Return value: None
*/
Public function selectDb ($ dbname)
{
$ This-> curr_db_name = $ dbname;
}

/**
* Create an index: if the index already exists, return.
*
* Parameters:
* $ Table_name: Table Name
* $ Index: index-array ("id" => 1)-create an index in the ascending order of the id field
* $ Index_param: Other conditions-whether the index is unique or not
*
* Return value:
* Success: true
* Failed: false
*/
Public function ensureIndex ($ table_name, $ index, $ index_param = array ())
{
$ Dbname = $ this-> curr_db_name;
$ Index_param ['safe '] = 1;
Try {
$ This-> mongo-> $ dbname-> $ table_name-> ensureIndex ($ index, $ index_param );
Return true;
}
Catch (except cursorexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
}

/**
* Insert record
*
* Parameters:
* $ Table_name: Table Name
* $ Record: record
*
* Return value:
* Success: true
* Failed: false
*/
Public function insert ($ table_name, $ record)
{
$ Dbname = $ this-> curr_db_name;
Try {
$ This-> mongo-> $ dbname-> $ table_name-> insert ($ record, array ('safe '=> true ));
Return true;
}
Catch (except cursorexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
}

/**
* Query the number of table records
*
* Parameters:
* $ Table_name: Table Name
*
* Return value: number of records in the table
*/
Public function count ($ table_name)
{
$ Dbname = $ this-> curr_db_name;
Return $ this-> mongo-> $ dbname-> $ table_name-> count ();
}

/**
* Update records
*
* Parameters:
* $ 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 (except cursorexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
}

/**
* Delete a record
*
* Parameters:
* $ Table_name: Table Name
* $ Condition: delete a condition
* $ Options: delete select-justOne
*
* Return value:
* Success: true
* Failed: false
*/
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 (except cursorexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}}

/**
* Query records
*
* Parameters:
* $ Table_name: Table Name
* $ Query_condition: Field Search Condition
* $ Result_condition: Query Result restriction condition-limit/sort
* $ Fields: obtains a field.
*
* Return value:
* Success: record set
* Failed: false
*/
Public function find ($ table_name, $ query_condition, $ result_condition = array (), $ 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 (except connectionexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
Catch (export cursortimeoutexception $ e)
{
$ This-> error = $ e-> getMessage ();
Return false;
}
Return $ result;
}

/**
* Search for a record
*
* Parameters:
* $ Table_name: Table Name
* $ Condition: search criteria
* $ Fields: obtains a field.
*
* Return value:
* Success: one record
* Failed: false
*/
Public function findOne ($ table_name, $ condition, $ fields = array ())
{
$ Dbname = $ this-> curr_db_name;
Return $ this-> mongo-> $ dbname-> $ table_name-> findOne ($ condition, $ fields );
}

/**
* Get the current error message
*
* Parameter: None
*
* Return value: current error message
*/
Public function getError ()
{
Return $ this-> error;
}

/*** Mongodb class ** examples:
* $ Mongo = new HMongodb ("127.0.0.1: 11223 ");
* $ Mongo-> selectDb ("test_db ");
* Create an index
* $ Mongo-> ensureIndex ("test_table", array ("id" => 1), array ('unique' => true ));
* Retrieve table records
* $ Mongo-> count ("test_table ");
* Insert record
* $ Mongo-> insert ("test_table", array ("id" => 2, "title" => "asdqw "));
* Update records
* $ Mongo-> update ("test_table", array ("id" => 1), array ("id" => 1, "title" => "bbb "));
* Update record-update if existing or non-existing
* $ Mongo-> update ("test_table", array ("id" => 1), array ("id" => 1, "title" => "bbb "), array ("upsert" => 1 ));
* Query records
* $ Mongo-> find ("c", array ("title" => "asdqw"), array ("start" => 2, "limit" => 2, "sort" => array ("id" => 1 )))
* Search for a record
* $ Mongo-> findOne ("$ mongo-> findOne (" ttt ", array (" id "=> 1 ))", array ("id" => 1 ));
* Delete a record
* $ Mongo-> remove ("ttt", array ("title" => "bbb "));
* Delete only one record
* $ Mongo-> remove ("ttt", array ("title" => "bbb"), array ("justOne" => 1 ));
* Get the Mongo operation error message
* $ 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.