MongoDB PHP数据库查询类

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介:
Java代码   收藏代码
  1. <?php    
  2. /*** Mongodb类** examples:    
  3. * $mongo = new HMongodb("127.0.0.1:11223");  
  4. * $mongo->selectDb("test_db");  
  5. * 创建索引  
  6. * $mongo->ensureIndex("test_table", array("id"=>1), array('unique'=>true));  
  7. * 获取表的记录  
  8. * $mongo->count("test_table");  
  9. * 插入记录  
  10. * $mongo->insert("test_table", array("id"=>2, "title"=>"asdqw"));  
  11. * 更新记录  
  12. * $mongo->update("test_table", array("id"=>1),array("id"=>1,"title"=>"bbb"));  
  13. * 更新记录-存在时更新,不存在时添加-相当于set  
  14. * $mongo->update("test_table", array("id"=>1),array("id"=>1,"title"=>"bbb"),array("upsert"=>1));  
  15. * 查找记录  
  16. * $mongo->find("c", array("title"=>"asdqw"), array("start"=>2,"limit"=>2,"sort"=>array("id"=>1)))  
  17. * 查找一条记录  
  18. * $mongo->findOne("$mongo->findOne("ttt", array("id"=>1))", array("id"=>1));  
  19. * 删除记录  
  20. * $mongo->remove("ttt", array("title"=>"bbb"));  
  21. * 仅删除一条记录  
  22. * $mongo->remove("ttt", array("title"=>"bbb"), array("justOne"=>1));  
  23. * 获取Mongo操作的错误信息  
  24. * $mongo->getError();  
  25. */    
  26.     
  27. class HMongodb {    
  28.     
  29.     //Mongodb连接    
  30.     var $mongo;    
  31.     
  32.     var $curr_db_name;    
  33.     var $curr_table_name;    
  34.     var $error;    
  35.     
  36.     /**  
  37.     * 构造函数  
  38.     * 支持传入多个mongo_server(1.一个出问题时连接其它的server 2.自动将查询均匀分发到不同server)  
  39.     *  
  40.     * 参数:  
  41.     * $mongo_server:数组或字符串-array("127.0.0.1:1111", "127.0.0.1:2222")-"127.0.0.1:1111"  
  42.     * $connect:初始化mongo对象时是否连接,默认连接  
  43.     * $auto_balance:是否自动做负载均衡,默认是  
  44.     *  
  45.     * 返回值:  
  46.     * 成功:mongo object  
  47.     * 失败:false  
  48.     */    
  49.     function __construct($mongo_server, $connect=true, $auto_balance=true)    
  50.     {    
  51.         if (is_array($mongo_server))    
  52.         {    
  53.             $mongo_server_num = count($mongo_server);    
  54.             if ($mongo_server_num > 1 && $auto_balance)    
  55.             {    
  56.                 $prior_server_num = rand(1, $mongo_server_num);    
  57.                 $rand_keys = array_rand($mongo_server,$mongo_server_num);    
  58.                 $mongo_server_str = $mongo_server[$prior_server_num-1];    
  59.                 foreach ($rand_keys as $key)    
  60.                 {    
  61.                     if ($key != $prior_server_num - 1)    
  62.                     {    
  63.                         $mongo_server_str .= ',' . $mongo_server[$key];    
  64.                     }    
  65.                 }    
  66.             }    
  67.             else    
  68.             {    
  69.                 $mongo_server_str = implode(',', $mongo_server);    
  70.             }                  }    
  71.         else    
  72.         {    
  73.             $mongo_server_str = $mongo_server;    
  74.         }    
  75.         try {    
  76.             $this->mongo = new Mongo($mongo_server, array('connect'=>$connect));    
  77.         }    
  78.         catch (MongoConnectionException $e)    
  79.         {    
  80.             $this->error = $e->getMessage();    
  81.             return false;    
  82.         }    
  83.     }    
  84.     
  85.     function getInstance($mongo_server, $flag=array())    
  86.     {    
  87.         static $mongodb_arr;    
  88.         if (emptyempty($flag['tag']))    
  89.         {    
  90.             $flag['tag'] = 'default';          }    
  91.         if (isset($flag['force']) && $flag['force'] == true)    
  92.         {    
  93.             $mongo = new HMongodb($mongo_server);    
  94.             if (emptyempty($mongodb_arr[$flag['tag']]))    
  95.             {    
  96.                 $mongodb_arr[$flag['tag']] = $mongo;    
  97.             }    
  98.             return $mongo;    
  99.         }    
  100.         else if (isset($mongodb_arr[$flag['tag']]) && is_resource($mongodb_arr[$flag['tag']]))    
  101.         {    
  102.             return $mongodb_arr[$flag['tag']];    
  103.         }    
  104.         else    
  105.         {    
  106.             $mongo = new HMongodb($mongo_server);    
  107.             $mongodb_arr[$flag['tag']] = $mongo;    
  108.             return $mongo;                  }          }    
  109.     
  110.     /**  
  111.     * 连接mongodb server  
  112.     *  
  113.     * 参数:无  
  114.     *  
  115.     * 返回值:  
  116.     * 成功:true  
  117.     * 失败:false  
  118.     */    
  119.     function connect()    
  120.     {    
  121.         try {    
  122.             $this->mongo->connect();    
  123.             return true;    
  124.         }    
  125.         catch (MongoConnectionException $e)    
  126.         {    
  127.             $this->error = $e->getMessage();    
  128.             return false;    
  129.         }    
  130.     }    
  131.     
  132.     /**  
  133.     * select db  
  134.     *  
  135.     * 参数:$dbname  
  136.     *  
  137.     * 返回值:无  
  138.     */    
  139.     function selectDb($dbname)    
  140.     {    
  141.         $this->curr_db_name = $dbname;    
  142.     }    
  143.     
  144.     /**  
  145.     * 创建索引:如索引已存在,则返回。  
  146.     *  
  147.     * 参数:  
  148.     * $table_name:表名  
  149.     * $index:索引-array("id"=>1)-在id字段建立升序索引  
  150.     * $index_param:其它条件-是否唯一索引等  
  151.     *  
  152.     * 返回值:  
  153.     * 成功:true  
  154.     * 失败:false  
  155.     */    
  156.     function ensureIndex($table_name, $index, $index_param=array())    
  157.     {    
  158.         $dbname = $this->curr_db_name;    
  159.         $index_param['safe'] = 1;    
  160.         try {    
  161.             $this->mongo->$dbname->$table_name->ensureIndex($index, $index_param);    
  162.             return true;    
  163.         }    
  164.         catch (MongoCursorException $e)    
  165.         {    
  166.             $this->error = $e->getMessage();    
  167.             return false;    
  168.         }    
  169.     }    
  170.     
  171.     /**  
  172.     * 插入记录  
  173.     *  
  174.     * 参数:  
  175.     * $table_name:表名  
  176.     * $record:记录  
  177.     *  
  178.     * 返回值:  
  179.     * 成功:true  
  180.     * 失败:false  
  181.     */    
  182.     function insert($table_name, $record)    
  183.     {    
  184.         $dbname = $this->curr_db_name;    
  185.         try {    
  186.             $this->mongo->$dbname->$table_name->insert($record, array('safe'=>true));    
  187.             return true;    
  188.         }    
  189.         catch (MongoCursorException $e)    
  190.         {    
  191.             $this->error = $e->getMessage();    
  192.             return false;    
  193.         }    
  194.     }    
  195.     
  196.     /**  
  197.     * 查询表的记录数  
  198.     *  
  199.     * 参数:  
  200.     * $table_name:表名  
  201.     *  
  202.     * 返回值:表的记录数  
  203.     */    
  204.     function count($table_name)    
  205.     {    
  206.         $dbname = $this->curr_db_name;    
  207.         return $this->mongo->$dbname->$table_name->count();    
  208.     }    
  209.     
  210.     /**  
  211.     * 更新记录  
  212.     *  
  213.     * 参数:  
  214.     * $table_name:表名  
  215.     * $condition:更新条件  
  216.     * $newdata:新的数据记录  
  217.     * $options:更新选择-upsert/multiple  
  218.     *  
  219.     * 返回值:  
  220.     * 成功:true  
  221.     * 失败:false  
  222.     */    
  223.     function update($table_name, $condition, $newdata, $options=array())    
  224.     {    
  225.         $dbname = $this->curr_db_name;    
  226.         $options['safe'] = 1;    
  227.         if (!isset($options['multiple']))    
  228.         {    
  229.             $options['multiple'] = 0;          }    
  230.         try {    
  231.             $this->mongo->$dbname->$table_name->update($condition, $newdata, $options);    
  232.             return true;    
  233.         }    
  234.         catch (MongoCursorException $e)    
  235.         {    
  236.             $this->error = $e->getMessage();    
  237.             return false;    
  238.         }          }    
  239.     
  240.     /**  
  241.     * 删除记录  
  242.     *  
  243.     * 参数:  
  244.     * $table_name:表名  
  245.     * $condition:删除条件  
  246.     * $options:删除选择-justOne  
  247.     *  
  248.     * 返回值:  
  249.     * 成功:true  
  250.     * 失败:false  
  251.     */    
  252.     function remove($table_name, $condition, $options=array())    
  253.     {    
  254.         $dbname = $this->curr_db_name;    
  255.         $options['safe'] = 1;    
  256.         try {    
  257.             $this->mongo->$dbname->$table_name->remove($condition, $options);    
  258.             return true;    
  259.         }    
  260.         catch (MongoCursorException $e)    
  261.         {    
  262.             $this->error = $e->getMessage();    
  263.             return false;    
  264.         }          }    
  265.     
  266.     /**  
  267.     * 查找记录  
  268.     *  
  269.     * 参数:  
  270.     * $table_name:表名  
  271.     * $query_condition:字段查找条件  
  272.     * $result_condition:查询结果限制条件-limit/sort等  
  273.     * $fields:获取字段  
  274.     *  
  275.     * 返回值:  
  276.     * 成功:记录集  
  277.     * 失败:false  
  278.     */    
  279.     function find($table_name, $query_condition, $result_condition=array(), $fields=array())    
  280.     {    
  281.         $dbname = $this->curr_db_name;    
  282.         $cursor = $this->mongo->$dbname->$table_name->find($query_condition, $fields);    
  283.         if (!emptyempty($result_condition['start']))    
  284.         {    
  285.             $cursor->skip($result_condition['start']);    
  286.         }    
  287.         if (!emptyempty($result_condition['limit']))    
  288.         {    
  289.             $cursor->limit($result_condition['limit']);    
  290.         }    
  291.         if (!emptyempty($result_condition['sort']))    
  292.         {    
  293.             $cursor->sort($result_condition['sort']);    
  294.         }    
  295.         $result = array();    
  296.         try {    
  297.             while ($cursor->hasNext())    
  298.             {    
  299.                 $result[] = $cursor->getNext();    
  300.             }    
  301.         }    
  302.         catch (MongoConnectionException $e)    
  303.         {    
  304.             $this->error = $e->getMessage();    
  305.             return false;    
  306.         }    
  307.         catch (MongoCursorTimeoutException $e)    
  308.         {    
  309.             $this->error = $e->getMessage();    
  310.             return false;    
  311.         }    
  312.         return $result;    
  313.     }    
  314.     
  315.     /**  
  316.     * 查找一条记录  
  317.     *  
  318.     * 参数:  
  319.     * $table_name:表名  
  320.     * $condition:查找条件  
  321.     * $fields:获取字段  
  322.     *  
  323.     * 返回值:  
  324.     * 成功:一条记录  
  325.     * 失败:false  
  326.     */    
  327.     function findOne($table_name, $condition, $fields=array())    
  328.     {    
  329.         $dbname = $this->curr_db_name;    
  330.         return $this->mongo->$dbname->$table_name->findOne($condition, $fields);    
  331.     }    
  332.     
  333.     /**  
  334.     * 获取当前错误信息  
  335.     *  
  336.     * 参数:无  
  337.     *  
  338.     * 返回值:当前错误信息  
  339.     */    
  340.     function getError()    
  341.     {    
  342.         return $this->error;    
  343.     }    
  344. }    
  345.     
  346. ?>  

数据库连接

Java代码   收藏代码
  1. //⑴默认格式  
  2. $m = new Mongo();  
  3. //这里采用默认连接本机的27017端口,当然你也可以连接远程主机如192.168.0.4:27017,如果端口是27017,端口可以省略  
  4. //⑵标准连接  
  5. $m = new Mongo("mongodb://${username}:${password}@localhost");   

选择想要的collection:

Java代码   收藏代码
  1. $mo = new Mongo();  
  2. $coll = $mo->selectCollection('db''mycoll');//得到一个collection对象  

插入数据(MongoCollection对象)

Java代码   收藏代码
  1. $coll = $mo->db->foo;  
  2. $a = array('a' => 'b');  
  3. $options = array('safe' => true);  
  4. $rs = $coll->insert($a, $options);  

更新数据库中的记录(MongoCollection对象)

Java代码   收藏代码
  1. $coll = $mo->db->coll;  
  2. $c = array('a' => 1's' => array('$lt' => 100));  
  3. $newobj = array('e' => 'f''x' => 'y');  
  4. $options = array('safe' => true'multiple' => true);  
  5. $rs = $coll->update($c, $newobj, $options);  

删除数据库中的记录(MongoCollection对象)

Java代码   收藏代码
  1. $coll = $mo->db->coll;  
  2. $c = array('a' => 1's' => array('$lt' => 100));  
  3. $options = array('safe' => true);  
  4. $rs = $coll->remove($c, $options);  

查询collection获得多条记录(MongoCollection类)

Java代码   收藏代码
  1. $coll = $mo->db->coll;  
  2. $query = array('s' => array('$lt' => 100));  
  3. $fields = array('a' => true'b' => true);  
  4. $rs = $coll->find($query, $fields);  

 查询collection获得单条记录(MongoCollection类)

Java代码   收藏代码
  1. $coll = $mo->db->coll;  
  2. $query = array('s' => array('$lt' => 100));  
  3. $fields = array('a' => true'b' => true);  
  4. $rs = $coll->findOne($query, $fields);  

针对游标对象MongoCursor的操作(MongoCursor类):

Java代码   收藏代码
  1. $cursor = $coll->find($query,$fields);  
  2. while($cursor->hasNext()){  
  3. $r = $cursor->getNext();  
  4.     var_dump($r);  
  5. }  
  6. //或者  
  7. $cursor = $coll->find($query,$fields);  
  8. foreache($cursor as $k=>$v){  
  9.     var_dump($v);  
  10. }  
  11. //或者  
  12. $cursor = $coll->find($query,$fields);  
  13. $array= iterator_to_array($cursor);  

删除一个数据库

Java代码   收藏代码
  1. $m -> dropDB("comedy");  

删除当前DB

Java代码   收藏代码
  1. $db = $mo->dbname;  
  2. $db->drop();  

列出所有可用数据库

Java代码   收藏代码
  1. $m->listDBs();   //无返回值  

获得当前数据库名

Java代码   收藏代码
  1. $db = $mo->dbname;  
  2. $db->_tostring();  
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
14天前
|
关系型数据库 MySQL 数据库
轻松入门MySQL:精准查询,巧用WHERE与HAVING,数据库查询如虎添翼(7)
轻松入门MySQL:精准查询,巧用WHERE与HAVING,数据库查询如虎添翼(7)
|
27天前
|
SQL 缓存 PHP
PHP技术探究:优化数据库查询效率的实用方法
本文将深入探讨PHP中优化数据库查询效率的实用方法,包括索引优化、SQL语句优化以及缓存机制的应用。通过合理的优化策略和技巧,可以显著提升系统性能,提高用户体验,是PHP开发者不容忽视的重要议题。
|
1月前
|
SQL 数据库 C#
C# .NET面试系列十一:数据库SQL查询(附建表语句)
#### 第1题 用一条 SQL 语句 查询出每门课都大于80 分的学生姓名 建表语句: ```sql create table tableA ( name varchar(10), kecheng varchar(10), fenshu int(11) ) DEFAULT CHARSET = 'utf8'; ``` 插入数据 ```sql insert into tableA values ('张三', '语文', 81); insert into tableA values ('张三', '数学', 75); insert into tableA values ('李四',
61 2
C# .NET面试系列十一:数据库SQL查询(附建表语句)
|
1月前
|
SQL 存储 JSON
阿里云数据库 SelectDB 内核 Apache Doris 2.1.0 版本发布:开箱盲测性能大幅优化,复杂查询性能提升 100%
亲爱的社区小伙伴们,Apache Doris 2.1.0 版本已于 2024 年 3 月 8 日正式发布,新版本开箱盲测性能大幅优化,在复杂查询性能方面提升100%,新增Arrow Flight接口加速数据读取千倍,支持半结构化数据类型与分析函数。异步多表物化视图优化查询并助力仓库分层建模。引入自增列、自动分区等存储优化,提升实时写入效率。Workload Group 资源隔离强化及运行时监控功能升级,保障多负载场景下的稳定性。新版本已经上线,欢迎大家下载使用!
阿里云数据库 SelectDB 内核 Apache Doris 2.1.0 版本发布:开箱盲测性能大幅优化,复杂查询性能提升 100%
|
1月前
|
存储 NoSQL Redis
【Redis】利用Redis List实现数据库分页快速查询
【Redis】利用Redis List实现数据库分页快速查询
82 0
|
14天前
|
缓存 监控 数据库
优化数据库查询性能的八大技巧
在今天的互联网时代,数据库是许多应用程序的核心组件之一。优化数据库查询性能是提升应用程序整体性能的关键。本文介绍了八种有效的技巧,帮助开发人员提高数据库查询性能,从而提升应用程序的响应速度和用户体验。
|
1月前
|
SQL 存储 关系型数据库
sql数据库查询语句大全
sql数据库查询语句大全
|
1月前
|
NoSQL 网络协议 MongoDB
Windows公网远程连接MongoDB数据库【无公网IP】
Windows公网远程连接MongoDB数据库【无公网IP】
|
1月前
|
存储 NoSQL 关系型数据库
一篇文章带你搞懂非关系型数据库MongoDB
一篇文章带你搞懂非关系型数据库MongoDB
55 0
|
1月前
|
人工智能 NoSQL MongoDB