`
gegewu0825
  • 浏览: 47286 次
社区版块
存档分类
最新评论

mongo 操作类封装

 
阅读更多

 

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


class mongo_db {

    private $config;
    private $connection;
    private $db;
    private $connection_string;
    private $host;
    private $port;
    private $user;
    private $pass;
    private $dbname;
    private $persist;
    private $persist_key;
    private $selects = array();
    private $wheres = array();
    private $sorts = array();
    private $limit = 999999;
    private $offset = 0;
	private $timeout = 200;
	private $key = 0;
	/**     * 	--------------------------------------------------------------------------------	 *	CONSTRUCTOR	 *	--------------------------------------------------------------------------------	 *	 *	Automatically check if the Mongo PECL extension has been installed/enabled.	 *	Generate the connection string and establish a connection to the MongoDB.	 */

    public function __construct() {
        if((IS_NOSQL != 1)){
            return;
        }
        if (!class_exists('Mongo')) {
            //$this->error("The MongoDB PECL extension has not been installed or enabled", 500);
        }
		$configs =wxcity_base::load_config("cache","mongo_db");
		$num = count($configs['connect']);
		$this->timeout = trim($configs['timeout']);
		$keys = wxcity_base::load_config('double');
		$this->key = $keys['mongo_db'];
		$this->config = $configs['connect'][$this->key];
		$status = $this->connect();
		if($status == false)
		{
			for($i = 1; $i < $num; $i++)
			{
				$n = $this->key + $i;
				$key = $n >= $num ? $n - $num : $n;
				$this->config = $configs['connect'][$key]; 
				$status = $this->connect();
				if($status!=false)
				{
					$keys['mongo_db'] = $key ;
					$this->key = $key;
					$data = "<?php\nreturn ".var_export($keys, true).";\n?>";
					file_put_contents(WHTY_PATH.'configs/double.php', $data, LOCK_EX);
					break;
				}
			}
		}
		if($status==false)
		{
			die('mongoDB not connect');
		}
    }
	
	function __destruct() {
		if((IS_NOSQL != 1)){
            return;
		}
		if($this->connection)
		{
			$this->connection->close();
		}
	}
	
	    /**     * 	--------------------------------------------------------------------------------	 *	CONNECT TO MONGODB	 *	--------------------------------------------------------------------------------	 *	 *	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() {
		$this->connection_string();
        $options = array('connect'=>true,'timeout'=>$this->timeout);
		try {
			$this->connection = new Mongo($this->connection_string, $options);
			$this->db = $this->connection->{$this->dbname};
			return($this);
		} catch (MongoConnectionException $e) {
			return false;
		}
		
    }
    /**     * 	--------------------------------------------------------------------------------	 *	BUILD CONNECTION STRING	 *	--------------------------------------------------------------------------------	 *	 *	Build the connection string from the config file.	 */
    private function connection_string() {
        $this->host = trim($this->config['hostname']);
        $this->port = trim($this->config['port']);
        $this->user = trim($this->config['username']);
        $this->pass = trim($this->config['password']);
        $this->dbname = trim($this->config['database']);
        $this->persist = trim($this->config['autoconnect']);
        $this->persist_key = trim($this->config['mongo_persist_key']);
		
        $connection_string = "mongodb://";
        if (empty($this->host)) {
            $this->error("The Host must be set to connect to MongoDB", 500);
        } if (empty($this->dbname)) {
            $this->error("The Database must be set to connect to MongoDB", 500);
        } if (!empty($this->user) && !empty($this->pass)) {
            $connection_string .= "{$this->user}:{$this->pass}@";
        } if (isset($this->port) && !empty($this->port)) {
            $connection_string .= "{$this->host}:{$this->port}";
        } else {
            $connection_string .= "{$this->host}";
        } $this->connection_string = trim($connection_string);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	Switch_db	 *	--------------------------------------------------------------------------------	 *	 *	Switch from default database to a different db	 */
    public function switch_db($database = '') {
        if (empty($database)) {
            $this->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) {
            $this->error("Unable to switch Mongo Databases: {$e->getMessage()}", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	SELECT FIELDS	 *	--------------------------------------------------------------------------------	 *	 *	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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	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 ((array)$wheres as $wh => $val) {
            $this->wheres[$wh] = $val;
        } return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE_IN PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE_NOT_IN PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is not in a given $in array().	 *	 *	@usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');	 */
    public function where_not_in($field = "", $in = array()) {
        $this->where_init($field);
        $this->wheres[$field]['$nin'] = $in;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE GREATER THAN PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is greater than $x	 *	 *	@usage = $this->mongo_db->where_gt('foo', 20);	 */
    public function where_gt($field = "", $x) {
        $this->where_init($field);
        $this->wheres[$field]['$gt'] = $x;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE GREATER THAN OR EQUAL TO PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is greater than or equal to $x	 *	 *	@usage = $this->mongo_db->where_gte('foo', 20);	 */
    public function where_gte($field = "", $x) {
        $this->where_init($field);
        $this->wheres[$field]['$gte'] = $x;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE LESS THAN PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is less than $x	 *	 *	@usage = $this->mongo_db->where_lt('foo', 20);	 */
    public function where_lt($field = "", $x) {
        $this->where_init($field);
        $this->wheres[$field]['$lt'] = $x;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE LESS THAN OR EQUAL TO PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE BETWEEN PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is between $x and $y	 *	 *	@usage = $this->mongo_db->where_between('foo', 20, 30);	 */
    public function where_between($field = "", $x, $y) {
        $this->where_init($field);
        $this->wheres[$field]['$gte'] = $x;
        $this->wheres[$field]['$lte'] = $y;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE BETWEEN AND NOT EQUAL TO PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is between but not equal to $x and $y	 *	 *	@usage = $this->mongo_db->where_between_ne('foo', 20, 30);	 */
    public function where_between_ne($field = "", $x, $y) {
        $this->where_init($field);
        $this->wheres[$field]['$gt'] = $x;
        $this->wheres[$field]['$lt'] = $y;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE NOT EQUAL TO PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is not equal to $x	 *	 *	@usage = $this->mongo_db->where_between('foo', 20, 30);	 */
    public function where_ne($field = "", $x) {
        $this->where_init($field);
        $this->wheres[$field]['$ne'] = $x;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE OR	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the value of a $field is in one or more values	 *	 *	@usage = $this->mongo_db->where_or('foo', array( 'foo', 'bar', 'blegh' );	 */
    public function where_or($field = "", $values) {
        $this->where_init($field);
        $this->wheres[$field]['$or'] = $values;
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE AND	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where the elements match the specified values	 *	 *	@usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' );	 */
    public function where_and($elements_values = array()) {
        foreach ((array)$elements_values as $element => $val) {
            $this->wheres[$element] = $val;
        } return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE MOD	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents where $field % $mod = $result	 *	 *	@usage = $this->mongo_db->where_mod( 'foo', 10, 1 );	 */
    public function where_mod($field, $num, $result) {
        $this->where_init($field);
        $this->wheres[$field]['$mod'] = array($num, $result);
        return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	*	Where size	*	--------------------------------------------------------------------------------	*	*	Get the documents where the size of a field is in a given $size int	*	*	@usage : $this->mongo_db->where_size('foo', 1)->get('foobar');	 */
    public function where_size($field = "", $size = "") {
        $this->_where_init($field);
        $this->wheres[$field]['$size'] = $size;
        return ($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	LIKE PARAMETERS	 *	--------------------------------------------------------------------------------	 *		 *	Get the documents where the (string) value of a $field is like a value. The defaults	 *	allow for a case-insensitive search.	 *	 *	@param $flags	 *	Allows for the typical regular expression flags:	 *		i = case insensitive	 *		m = multiline	 *		x = can contain comments	 *		l = locale	 *		s = dotall, "." matches everything, including newlines	 *		u = match unicode	 *	 *	@param $enable_start_wildcard	 *	If set to anything other than TRUE, a starting line character "^" will be prepended	 *	to the search value, representing only searching for a value at the start of 	 *	a new line.	 *	 *	@param $enable_end_wildcard	 *	If set to anything other than TRUE, an ending line character "$" will be appended	 *	to the search value, representing only searching for a value at the end of 	 *	a line.	 *	 *	@usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE);	 */
    public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
        $field = (string) trim($field);
        $this->where_init($field);
        $value = (string) trim($value);
        $value = quotemeta($value);
        if ($enable_start_wildcard !== TRUE) {
            $value = "^" . $value;
        } if ($enable_end_wildcard !== TRUE) {
            $value .= "$";
        } $regex = "/$value/$flags";
        $this->wheres[$field] = new MongoRegex($regex);
        return($this);
    }

    public function wheres($where){
        $this->wheres = $where;
    }

    /**     * 	--------------------------------------------------------------------------------	 *	ORDER BY PARAMETERS	 *	--------------------------------------------------------------------------------	 *	 *	Sort the documents based on the parameters passed. 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->where_between('foo', 20, 30);	 */
    public function order_by($fields = array()) {
		if (!is_array($fields) || !count($fields)) return ;
        foreach ($fields as $col => $val) {
            if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
                $this->sorts[$col] = -1;
            } else {
                $this->sorts[$col] = 1;
            }
        } return($this);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	LIMIT DOCUMENTS	 *	--------------------------------------------------------------------------------	 *	 *	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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	OFFSET DOCUMENTS	 *	--------------------------------------------------------------------------------	 *	 *	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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	GET_WHERE	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents based upon the passed parameters	 *	 *	@usage = $this->mongo_db->get_where('foo', array('bar' => 'something'));	 */
    public function get_where($collection = "", $where = array(), $limit = 99999, $orderby=array()) {
        if (is_array($orderby) || !empty($orderby)) {
            $order_by = $this->order_by($order_by);
        }
        return($this->where($where)->limit($limit)->get($collection));
    }
    public function selectA($collection = "", $limit = 99999, $orderby=array()) {
        if(intval($limit)<1){
            $limit = 999999;
        }
        $order_by = $this->order_by($orderby);
        $re = $this->limit($limit)->get($collection);
        $this->clear();
        return (array)$re;
    }

    public function listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
        $page = max(intval($page), 1);
        $offset = $pagesize * ($page - 1);
        $pagesizes = $offset + $pagesize;
        $this->offset($offset);
        $order_by = $this->order_by($orderby);
        $re = $this->limit($pagesize)->get($collection);
        $this->limit(999999);
        $count = $this->count($collection);
        $this->pages = pages($count, $page, $pagesize);
        return (array)$re;
    }

    /**     * 	--------------------------------------------------------------------------------	 *	GET	 *	--------------------------------------------------------------------------------	 *	 *	Get the documents based upon the passed parameters	 *	 *	@usage = $this->mongo_db->get('foo', array('bar' => 'something'));	 */
    public function get($collection = "") {
        if (empty($collection)) {
            $this->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;
        return($returns);
    }

	public function getMy($collection = "") {
        if (empty($collection)) {
            $this->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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	COUNT	 *	--------------------------------------------------------------------------------	 *	 *	Count the documents based upon the passed parameters	 *	 *	@usage = $this->mongo_db->get('foo');	 */
    public function count($collection = "") {
        if (empty($collection)) {
            $this->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);
    }

    /**     * 	--------------------------------------------------------------------------------	 *	INSERT	 *	--------------------------------------------------------------------------------	 *	 *	Insert a new document into the passed collection	 *	 *	@usage = $this->mongo_db->insert('foo', $data = array());	 */
    public function insert($collection = "", $data = array(), $name='ID') {
        if (empty($collection)) {
            $this->error("No Mongo collection selected to insert into", 500);
        } if (count($data) == 0 || !is_array($data)) {
            $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
        } try {
		/**
			wxcity_base::load_sys_class('whtysqs','',0); 
			$mongoseq_class = new whtysqs('creaseidsqs');
            $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
		**/
			$re = put_sqs('list_mongo_creaseidsqs','1');
			if(is_numeric($re)){
				$re++;
				$data[$name] = intval($re);
            }else{
				$data[$name] = intval(time());
                //die('mongosqs error');
            }
            $this->db->{$collection}->insert($data, array('fsync' => TRUE)); 
            $this->clear();
            return $data[$name];
        } catch (MongoCursorException $e) {
            $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
        }
    }

	public function insertWithId($collection = "", $data = array()) {
        if (empty($collection)) {
            $this->error("No Mongo collection selected to insert into", 500);
        } if (count($data) == 0 || !is_array($data)) {
            $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
        } try {
            $this->db->{$collection}->insert($data, array('fsync' => TRUE)); 
            $this->clear();
            return 1;
        } catch (MongoCursorException $e) {
            $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
        }
    }
    /**     * 	--------------------------------------------------------------------------------	 *	UPDATE	 *	--------------------------------------------------------------------------------	 *	 *	Update a document into the passed collection	 *	 *	@usage = $this->mongo_db->update('foo', $data = array());	 */
    public function update($collection = "", $data = array()) {
        if (empty($collection)) {
            $this->error("No Mongo collection selected to update", 500);
        } if (count($data) == 0 || !is_array($data)) {
            $this->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' => FALSE));
			$this->clear();
            return(TRUE);
        } catch (MongoCursorException $e) {
            $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	UPDATE_ALL	 *	--------------------------------------------------------------------------------	 *	 *	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)) {
            $this->error("No Mongo collection selected to update", 500);
        } if (count($data) == 0 || !is_array($data)) {
            $this->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));
            return(TRUE);
        } catch (MongoCursorException $e) {
            $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	DELETE	 *	--------------------------------------------------------------------------------	 *	 *	delete document from the passed collection based upon certain criteria	 *	 *	@usage = $this->mongo_db->delete('foo', $data = array());	 */
    public function delete($collection = "") {
        if (empty($collection)) {
            $this->error("No Mongo collection selected to delete from", 500);
        } try {
            $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => TRUE));
            $this->clear();
            return(TRUE);
        } catch (MongoCursorException $e) {
            $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	DELETE_ALL	 *	--------------------------------------------------------------------------------	 *	 *	Delete all documents from the passed collection based upon certain criteria	 *	 *	@usage = $this->mongo_db->delete_all('foo', $data = array());	 */
    public function delete_all($collection = "") {
        if (empty($collection)) {
            $this->error("No Mongo collection selected to delete from", 500);
        } try {
            $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => FALSE));
            return(TRUE);
        } catch (MongoCursorException $e) {
            $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	ADD_INDEX	 *	--------------------------------------------------------------------------------	 *	 *	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)) {
            $this->error("No Mongo collection specified to add index to", 500);
        } if (empty($keys) || !is_array($keys)) {
            $this->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 {
            $this->error("An error occured when trying to add an index to MongoDB Collection", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	REMOVE_INDEX	 *	--------------------------------------------------------------------------------	 *	 *	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)) {
            $this->error("No Mongo collection specified to remove index from", 500);
        } if (empty($keys) || !is_array($keys)) {
            $this->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 {
            $this->error("An error occured when trying to remove an index from MongoDB Collection", 500);
        }
    }

    /**     * 	--------------------------------------------------------------------------------	 *	REMOVE_ALL_INDEXES	 *	--------------------------------------------------------------------------------	 *	 *	Remove all indexes from a collection.	 *	 *	@usage = $this->mongo_db->remove_all_index($collection);	 */
    public function remove_all_indexes($collection = "") {
        if (empty($collection)) {
            $this->error("No Mongo collection specified to remove all indexes from", 500);
        } $this->db->{$collection}->deleteIndexes();
        $this->clear();
        return($this);
    }

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

    /**     * 	--------------------------------------------------------------------------------	 *	DROP COLLECTION	 *	--------------------------------------------------------------------------------	 *	 *	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)) {
            $this->error("No Mongo collection specified to drop from database", 500);
        } $this->db->{$collection}->drop();
        return TRUE;
    }

    /**     * 	--------------------------------------------------------------------------------	 *	CLEAR	 *	--------------------------------------------------------------------------------	 *	 *	Resets the class variables to default settings	 */
    private function clear() {
        $this->selects = array();
        $this->wheres = array();
        $this->limit = NULL;
        $this->offset = NULL;
        $this->sorts = array();
    }

    /**     * 	--------------------------------------------------------------------------------	 *	WHERE INITIALIZER	 *	--------------------------------------------------------------------------------	 *	 *	Prepares parameters for insertion in $wheres array().	 */
    private function where_init($param) {
        if (!isset($this->wheres[$param])) {
            $this->wheres[$param] = array();
        }
    }

    public function error($str, $t) {
        echo $str;
        exit;
    }

}
   
?> 
使用时候 先where得到条件 在进行操作
			$table_name=trim(strtolower($this->table_name));
			$this->mongo_db->where($where);
			$order=!empty($order)?array('AID'=>'DESC'):array('AID'=>'ASC');//升序降序
			$infos=$this->mongo_db->listinfo($table_name,$order,$page,$pagesize);
分享到:
评论

相关推荐

    java针对mongo操作的封装,完全面向对象,无需修改,可直接使用

    完全面向对象的mongo封装,maven工程源码,可直接install导出jar包引用,支持基本的增删改查和分页等,使用反射对javaBean实体进行映射,所有方法参数只需要传javaBean就行了,支持带密码连接,即拿即用,无需修改。

    Mongo封装类

    "Mongo封装类"指的是开发者为了简化操作,通常会创建自己的类库来封装MongoDB PHP驱动的功能,这样可以提高代码的可读性和可维护性。 在提供的信息中,提到了两个可以直接运行的类:`TmongoDB`和一个未明确命名的...

    mongoTemplate工具类Dao层方法封装.zip

    这个资源包“mongoTemplate工具类Dao层方法封装.zip”显然提供了两种版本的MongoTemplate操作集合的代码示例,旨在帮助开发者更高效地进行数据访问层(Dao层)的开发。以下是关于MongoTemplate及它在 Dao 层中使用的...

    基于spring data mongo封装的API,让开发人员不用知道mongo

    本项目基于Spring Data MongoDB封装了一套API,旨在让业务开发人员更加专注于业务逻辑,而非数据库操作。 首先,Spring Data MongoDB的核心在于Repository抽象,它提供了一种声明式的方式来处理数据库的CRUD(创建...

    MONGODB基本操作封装类

    将mongodb的基本操作,增删查询等封装为一个基本类供人调用

    mongodb 操作基础类 封装

    Morphia一个nosql的ORM框架 对此二次封装

    java-mongodb底层封装

    这些方法是封装后对外提供的基本操作,具体的实现会涉及到MongoClient、MongoDatabase和MongoCollection等类的使用。 通过这样的底层封装,开发人员可以专注于业务逻辑,而无需过多关注数据库操作的细节,提高了...

    mongo php类

    "mongo php类"指的是PHP中用于操作MongoDB的类库,允许开发者在PHP应用程序中执行CRUD(创建、读取、更新、删除)操作。 MongoDB类和TmongoDB类是两种不同的PHP类,用于连接和管理MongoDB数据库。MongoDB类是PHP...

    Excell导入Mongo工具类.rar

    标题中的"Excell导入Mongo工具类.rar"表明这是一个与Java编程相关的项目,它提供了一个工具类用于将Excel数据导入MongoDB数据库。MongoDB是一个流行的NoSQL数据库,它以JSON格式的文档存储数据,而非传统的表格结构...

    MongoDB操作类封装实例代码

    MongoDB操作类封装实例代码详解 在开发过程中,数据库操作的封装可以提高代码的可读性和复用性,降低维护成本。本篇文章将详细介绍如何针对MongoDB数据库进行操作类的封装,以方便日常开发中的数据操作。MongoDB是...

    PHP操作Mongodb封装类完整实例

    * 2:其它更高级的操作可通过 $this-&gt;getMongo() 得到原生的对象,更多API请自行查阅 Mongo PHP手册,后续版本将会对增加更多的原生API封装 * 3:该类所有API接口中的 $query 查询参数的使用请以下有关 [查询条件...

    详解nodejs操作mongodb数据库封装DB类

    这个DB类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评。... * mongoose操作类(封装mongodb) */ var fs = require('fs'); var path = require('path'); var mongoose = require('mongoos

    mongo可视化工具

    这些DLL文件是.NET程序集,封装了各种UI控件和数据操作逻辑。 ComponentFactory.Krypton.Toolkit.dll是Krypton Toolkit的组件库,这是一个用于.NET Windows Forms和WPF应用的UI设计包,可以提供自定义的、一致的...

    mongoDB DAO层封装

    MongoDB DAO层封装是数据库操作的重要一环,它在应用程序与数据库之间建立了一层抽象,使得数据访问更加简便和高效。在这个项目中,我们主要基于MongoDB 3.0版本和Spring Data 1.5进行整合,实现了DAO层的封装。下面...

    spring-data使用mongodbTemplate对MongoDB进行读写操作

    它是MongoDB操作的抽象层,封装了大量的CRUD(创建、读取、更新、删除)操作,以及更复杂的查询和聚合功能。在`App.java`中,你可以看到如何初始化和使用`MongoDBTemplate`。通常,你需要通过`ApplicationContext`...

    solr-mongo-import-1.0和1.1以及mongo-Java-driver

    `solr-mongo-importer-1.1.0.jar`和`solr-mongo-importer-1.0.0.jar`就是这两个版本的实现,它们包含了导入过程所需的所有类和库,以便与Solr服务器进行通信并执行数据迁移。 `mongo-java-driver`则是MongoDB官方...

    mongo-cxx-driver-releases-v3.2开发所需lib、dll以及头文件

    `mongo-c-driver`包含了连接管理、认证、数据序列化等功能,而`mongo-cxx-driver`在其之上构建了更高级别的C++封装,提供了更符合C++编程习惯的API。在C++驱动程序中,你需要`mongo-c-driver`的库和头文件来完成底层...

    php_mongo:长期维护的mongodb封装类1.0

    《php_mongo:长期维护的MongoDB封装类1.0详解》 在现代Web开发中,PHP作为一种广泛使用的脚本语言,与NoSQL数据库的结合日益紧密,其中MongoDB是颇受欢迎的选择。为了方便PHP开发者更高效地操作MongoDB,出现了一...

    php操作mongodb封装类与用法实例

    本文实例讲述了php操作mongodb封装类与用法。分享给大家供大家参考,具体如下: 近来学习了mongodb,刚好是做php开发的,随便写了php操作mongodb的封装类. &lt;?php /** * Created by PhpStorm. * User: lee * ...

    php封装的mongodb操作类代码

    标题中的"php封装的mongodb操作类代码"指的是在PHP中为MongoDB数据库创建的一个自定义类,用于简化和封装MongoDB的操作。这个类通常会包含连接数据库、执行查询、插入数据、更新数据以及删除数据等常见操作的方法。...

Global site tag (gtag.js) - Google Analytics