本文实例讲述了php操作MongoDB类的方法。分享给大家供大家参考。具体如下:
1. MyMongo.php文件:
<?php /** * 仿写CI的MongoDB * @author sparkHuang 2011-11-03 * */ class MyMongo { private $mongo_config = "mongo_config.php"; private $connection; private $db; private $mongo_connect_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; public function __construct() { if ( ! class_exists('Mongo')) { $this->log_error("The MongoDB PECL extentiosn has not been installed or enabled."); exit; } $this->connection_string(); $this->connect(); } /** * 更改数据库 * */ public function switch_db($database = '') { if (empty($database)) { $this->log_error("To switch MongoDB databases, a new database name must be specified"); exit; } $this->dbname = $database; try { $this->db = $this->connection->{$this->dbname}; return true; } catch(Exception $e) { $this->log_error("Unable to switch Mongo Databases: {$e->getMessage()}"); exit; } } /** * 设置select字段 * */ public function select($includs = array(), $excludes = array()) { if ( ! is_array($includs)) { $includs = (array)$includs; } if ( ! is_array($excludes)) { $excludes = (array)$excludes; } if ( ! empty($includs)) { foreach ($includs as $col) { $this->selects[$col] = 1; } } else { foreach ($excludes as $col) { $this->selects[$col] = 0; } } return($this); } /** * where条件查询判断 * * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar'); * */ public function where($wheres = array()) { if ( ! is_array($wheres)) { $wheres = (array)$wheres; } if ( ! empty($wheres)) { foreach($wheres as $wh => $val) { $this->wheres[$wh] = $val; } } return($this); } /** * where ... in .. 条件查询判断 * * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo'))->get('foobar'); * */ public function where_in($field = '', $in = array()) { $this->where_init($field); $this->wheres[$field]['$in'] = $in; return($this); } /** * where ... not in .. 条件查询判断 * * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo'))->get('foobar'); * */ public function where_not_in($field = '', $in = array()) { $this->where_init($field); $this->wheres[$field]['$nin'] = $in; return($this); } /** * where ... $field > $x .. 条件查询判断 * * @usage = $this->mongo_db->where_gt('foo', 20)->get('foobar'); * */ public function where_gt($field = '', $x) { $this->where_init($field); $this->wheres[$field]['$gt'] = $x; return($this); } /** * where ... $field >= $x .. 条件查询判断 * * @usage = $this->mongo_db->where_gte('foo', 20)->get('foobar'); * */ public function where_gte($field = '', $x) { $this->where_init($field); $this->wheres[$field]['$gte'] = $x; return($this); } /** * where ... $field < $x .. 条件查询判断 * * @usage = $this->mongo_db->where_lt('foo', 20)->get('foobar'); * */ public function where_lt($field = '', $x) { $this->where_init($field); $this->wheres[$field]['$lt'] = $x; return($this); } /** * where ... $field <= $x .. 条件查询判断 * * @usage = $this->mongo_db->where_lte('foo', 20)->get('foobar'); * */ public function where_lte($field = '', $x) { $this->where_init($field); $this->wheres[$field]['$lte'] = $x; return($this); } /** * where ... $field >= $x AND $field <= $y .. 条件查询判断 * * @usage = $this->mongo_db->where_between('foo', 20, 30)->get('foobar'); * */ public function where_between($field = '', $x, $y) { $this->where_init($field); $this->wheres[$field]['$gte'] = $x; $this->wheres[$field]['$lte'] = $y; return($this); } /** * where ... $field > $x AND $field < $y .. 条件查询判断 * * @usage = $this->mongo_db->where_between_ne('foo', 20, 30)->get('foobar'); * */ 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 ... $field <> $x .. 条件查询判断 * * @usage = $this->mongo_db->where_ne('foo', 20)->get('foobar'); * */ public function where_ne($field = '', $x) { $this->where_init($field); $this->wheres[$field]['$ne'] = $x; return($this); } /** * where ... or .. 条件查询判断 * * @usage = $this->mongo_db->where_or('foo', array('foo', 'bar'))->get('foobar'); * */ public function where_or($field = '', $values) { $this->where_init($field); $this->wheres[$field]['$or'] = $values; return($this); } /** * where ... and .. 条件查询判断 * * @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' ); */ public function where_and( $elements_values = array() ) { foreach ( $elements_values as $element => $val ) { $this->wheres[$element] = $val; } return($this); } /** * where $field % $num = $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条件查询(PHP中定义MongoRegex类实现) * * @usage : $this->mongo_db->like('foo', 'bar', 'im', false, false)->get(); */ public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = true, $enable_end_wildcard = true) { $field = (string)$field; $this->where_init($field); $value = (string)$value; $value = quotmeta($value); if (true !== $enable_start_wildcard) { $value = "^".$value; } if (true !== $enable_end_wildcard) { $value .= "$"; } $regex = "/$value/$flags"; $this->wheres[$field] = new MongoRegex($regex); return($this); } /** * order排序( 1 => ASC, -1 => DESC) * * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->order_by(array("age" => 1)); */ public function order_by($fields = array()) { 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 * * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->limit(10); */ public function limit($x = 999999) { if ($x !== NULL && is_numeric($x) && $x >= 1) { $this->limit = (int)$x; } return($this); } /** * offset * * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->offset(10); */ public function offset($x = 0) { if($x !== NULL && is_numeric($x) && $x >= 1) { $this->offset = (int) $x; } return($this); } /** * get_where * * @usage: $this->mongo_db->get_where('foo', array('bar' => 'something')); */ public function get_where($collection = "", $where = array(), $limit = 999999) { return($this->where($where)->limit($limit)->get($collection)); } /** * get * * @usage: $this->mongo_db->where(array('name' => 'tom'))->get('foo'); */ public function get($collection) { if (empty($collection)) { $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed"); exit; } $results = array(); $results = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts); $returns = array(); foreach($results as $result) { $returns[] = $result; } $this->clear(); return($returns); } /** * count * * @usage: $this->db->get_where('foo', array('name' => 'tom'))->count('foo'); */ public function count($collection) { if (empty($collection)) { $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed"); exit; } $count = $this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count(); $this->clear(); return($count); } /** * insert * * @usage: $this->mongo_db->insert('foo', array('name' => 'tom')); */ public function insert($collection = "", $data = array()) { if (empty($collection)) { $this->log_error("No Mongo collection selected to delete from"); exit; } if (count($data) == 0 || ! is_array($data)) { $this->log_error("Nothing to insert into Mongo collection or insert is not an array"); exit; } try { $this->db->{$collection}->insert($data, array('fsync' => true)); if (isset($data['_id'])) { return($data['_id']); } else { return(false); } } catch(MongoCursorException $e) { $this->log_error("Insert of data into MongoDB failed: {$e->getMessage()}"); exit; } } /** * update : 利用MongoDB的 $set 实现 * * @usage : $this->mongo_db->where(array('name' => 'tom'))->update('foo', array('age' => 24)) */ public function update($collection = "", $data = array()) { if (empty($collection)) { $this->log_error("No Mongo collection selected to delete from"); exit; } if (count($data) == 0 || ! is_array($data)) { $this->log_error("Nothing to update in Mongo collection or update is not an array"); exit; } try { $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => false)); //注意: multiple为false return(true); } catch(MongoCursorException $e) { $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}"); exit; } } /** * update_all : 利用MongoDB的 $set 实现 * * @usage : $this->mongo_db->where(array('name' => 'tom'))->update_all('foo', array('age' => 24)); */ public function update_all($collection = "", $data = array()) { if (empty($collection)) { $this->log_error("No Mongo collection selected to delete from"); exit; } if (count($data) == 0 || ! is_array($data)) { $this->log_error("Nothing to update in Mongo collection or update is not an array"); exit; } try { $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => true)); //注意: multiple为true return(true); } catch(MongoCursorException $e) { $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}"); exit; } } /** * delete * * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete('foo'); */ public function delete($collection = "") { if (empty($collection)) { $this->log_error("No Mongo collection selected to delete from"); exit; } try { $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => true)); //注意justOne为true; } catch(MongoCursorException $e) { $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}"); exit; } } /** * delete_all * * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete_all('foo'); */ public function delete_all($collection = "") { if (empty($collection)) { $this->log_error("No Mongo collection selected to delete from"); exit; } try { $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => false)); //注意justOne为false; } catch(MongoCursorException $e) { $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}"); exit; } } /** * add_index * * @usage : $this->mongo_db->add_index('foo', array('first_name' => 'ASC', 'last_name' => -1), array('unique' => true))); */ public function add_index($collection, $keys = array(), $options = array()) { if (empty($collection)) { $this->log_error("No Mongo collection specified to add index to"); exit; } if (empty($keys) || ! is_array($keys)) { $this->log_error("Index could not be created to MongoDB Collection because no keys were specified"); exit; } foreach($keys as $col => $val) { if ($val == -1 || $val == false || strtolower($val) == 'desc') { $keys[$col] = -1; } else { $keys[$col] = 1; } } //在此没有对$options数组的有效性进行验证 if (true == $this->db->{$collection}->ensureIndex($keys, $options)) { $this->clear(); return($this); } else { $this->log_error("An error occured when trying to add an index to MongoDB Collection"); exit; } } /** * remove_index * * @usage : $this->mongo_db->remove_index('foo', array('first_name' => 'ASC', 'last_name' => -1)) */ public function remove_index($collection = "", $keys = array()) { if (empty($collection)) { $this->log_error("No Mongo collection specified to add index to"); exit; } if (empty($keys) || ! is_array($keys)) { $this->log_error("Index could not be created to MongoDB Collection because no keys were specified"); exit; } if ($this->db->{$collection}->deleteIndex($keys)) { $this->clear(); return($this); } else { $this->log_error("An error occured when trying to add an index to MongoDB Collection"); exit; } } /** * remove_all_index * * @usage : $this->mongo_db->remove_all_index('foo', array('first_name' => 'ASC', 'last_name' => -1)) */ public function remove_all_index($collection = "", $keys = array()) { if (empty($collection)) { $this->log_error("No Mongo collection specified to add index to"); exit; } if (empty($keys) || ! is_array($keys)) { $this->log_error("Index could not be created to MongoDB Collection because no keys were specified"); exit; } if ($this->db->{$collection}->deleteIndexes($keys)) { $this->clear(); return($this); } else { $this->log_error("An error occured when trying to add an index to MongoDB Collection"); exit; } } /** * list_indexes * * @usage : $this->mongo_db->list_indexes('foo'); */ public function list_indexes($collection = "") { if (empty($collection)) { $this->log_error("No Mongo collection specified to add index to"); exit; } return($this->db->{$collection}->getIndexInfo()); } /** * drop_collection * * @usage : $this->mongo_db->drop_collection('foo'); */ public function drop_collection($collection = "") { if (empty($collection)) { $this->log_error("No Mongo collection specified to add index to"); exit; } $this->db->{$collection}->drop(); return(true); } /** * 生成连接MongoDB 参数字符串 * */ private function connection_string() { include_once($this->mongo_config); $this->host = trim($config['host']); $this->port = trim($config['port']); $this->user = trim($config['user']); $this->pass = trim($config['pass']); $this->dbname = trim($config['dbname']); $this->persist = trim($config['persist']); $this->persist_key = trim($config['persist_key']); $connection_string = "mongodb://"; if (empty($this->host)) { $this->log_error("The Host must be set to connect to MongoDB"); exit; } if (empty($this->dbname)) { $this->log_error("The Database must be set to connect to MongoDB"); exit; } 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); } /** * 连接MongoDB 获取数据库操作句柄 * */ private function connect() { $options = array(); if (true === $this->persist) { $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) { $this->log_error("Unable to connect to MongoDB: {$e->getMessage()}"); } } /** * 初始化清理部分成员变量 * */ private function clear() { $this->selects = array(); $this->wheres = array(); $this->limit = NULL; $this->offset = NULL; $this->sorts = array(); } /** * 依据字段名初始化处理$wheres数组 * */ private function where_init($param) { if ( ! isset($this->wheres[$param])) { $this->wheres[$param] = array(); } } /** * 错误记录 * */ private function log_error($msg) { $msg = "[Date: ".date("Y-m-i H:i:s")."] ".$msg; @file_put_contents("./error.log", print_r($msg."\n", true), FILE_APPEND); } } /* End of MyMongo.php */
2. mongo_config.php配置文件:
<?php $config["host"] = "localhost"; $config["user"] = ""; $config["pass"] = ""; $config["port"] = 27017; $config["dbname"] = "test"; $config['persist'] = TRUE; $config['persist_key'] = 'ci_mongo_persist'; /*End of mongo_config.php*/
3. MyMongoDemo.php文件:
<?php include_once("MyMongo.php"); $conn = new MyMongo(); //删除所有记录 $conn->delete_all("blog"); //插入第一条记录 $value = array("name" => "小明", "age" => 25, "addr" => array("country" => "中国", "province" => "广西", "city" => "桂林")); $conn->insert("blog", $value); var_dump($conn->select(array("name", "age"))->get("blog")); var_dump($conn->get("blog")); /* End of MyMongoDemo.php */
希望本文所述对大家的php程序设计有所帮助。

PHP在現代編程中仍然是一個強大且廣泛使用的工具,尤其在web開發領域。 1)PHP易用且與數據庫集成無縫,是許多開發者的首選。 2)它支持動態內容生成和麵向對象編程,適合快速創建和維護網站。 3)PHP的性能可以通過緩存和優化數據庫查詢來提升,其廣泛的社區和豐富生態系統使其在當今技術棧中仍具重要地位。

在PHP中,弱引用是通過WeakReference類實現的,不會阻止垃圾回收器回收對象。弱引用適用於緩存系統和事件監聽器等場景,需注意其不能保證對象存活,且垃圾回收可能延遲。

\_\_invoke方法允許對象像函數一樣被調用。 1.定義\_\_invoke方法使對象可被調用。 2.使用$obj(...)語法時,PHP會執行\_\_invoke方法。 3.適用於日誌記錄和計算器等場景,提高代碼靈活性和可讀性。

Fibers在PHP8.1中引入,提升了並發處理能力。 1)Fibers是一種輕量級的並發模型,類似於協程。 2)它們允許開發者手動控制任務的執行流,適合處理I/O密集型任務。 3)使用Fibers可以編寫更高效、響應性更強的代碼。

PHP社區提供了豐富的資源和支持,幫助開發者成長。 1)資源包括官方文檔、教程、博客和開源項目如Laravel和Symfony。 2)支持可以通過StackOverflow、Reddit和Slack頻道獲得。 3)開發動態可以通過關注RFC了解。 4)融入社區可以通過積極參與、貢獻代碼和學習分享來實現。

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

PHP不是在消亡,而是在不斷適應和進化。 1)PHP從1994年起經歷多次版本迭代,適應新技術趨勢。 2)目前廣泛應用於電子商務、內容管理系統等領域。 3)PHP8引入JIT編譯器等功能,提升性能和現代化。 4)使用OPcache和遵循PSR-12標準可優化性能和代碼質量。

PHP的未來將通過適應新技術趨勢和引入創新特性來實現:1)適應云計算、容器化和微服務架構,支持Docker和Kubernetes;2)引入JIT編譯器和枚舉類型,提升性能和數據處理效率;3)持續優化性能和推廣最佳實踐。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 Linux新版
SublimeText3 Linux最新版

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能