MongoDB PHP数据库查询类

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介:
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();  
相关文章
|
6月前
|
人工智能 安全 机器人
无代码革命:10分钟打造企业专属数据库查询AI机器人
随着数字化转型加速,企业对高效智能交互解决方案的需求日益增长。阿里云AppFlow推出的AI助手产品,借助创新网页集成技术,助力企业打造专业数据库查询助手。本文详细介绍通过三步流程将AI助手转化为数据库交互工具的核心优势与操作指南,包括全场景适配、智能渲染引擎及零代码配置等三大技术突破。同时提供Web集成与企业微信集成方案,帮助企业实现便捷部署与安全管理,提升内外部用户体验。
657 12
无代码革命:10分钟打造企业专属数据库查询AI机器人
|
8月前
|
Cloud Native 关系型数据库 分布式数据库
|
8月前
|
并行计算 关系型数据库 MySQL
如何用 esProc 将数据库表转储提速查询
当数据库查询因数据量大或繁忙变慢时,可借助 esProc 将数据导出为文件进行计算,大幅提升性能。以 MySQL 的 3000 万行订单数据为例,两个典型查询分别耗时 17.69s 和 63.22s。使用 esProc 转储为二进制行存文件 (btx) 或列存文件 (ctx),结合游标过滤与并行计算,性能显著提升。例如,ctx 并行计算将原查询时间缩短至 0.566s,TopN 运算提速达 30 倍。esProc 的简洁语法和高效文件格式,特别适合历史数据的复杂分析场景。
|
9月前
|
SQL 关系型数据库 MySQL
如何优化SQL查询以提高数据库性能?
这篇文章以生动的比喻介绍了优化SQL查询的重要性及方法。它首先将未优化的SQL查询比作在自助餐厅贪多嚼不烂的行为,强调了只获取必要数据的必要性。接着,文章详细讲解了四种优化策略:**精简选择**(避免使用`SELECT *`)、**专业筛选**(利用`WHERE`缩小范围)、**高效联接**(索引和限制数据量)以及**使用索引**(加速搜索)。此外,还探讨了如何避免N+1查询问题、使用分页限制结果、理解执行计划以及定期维护数据库健康。通过这些技巧,可以显著提升数据库性能,让查询更高效流畅。
|
9月前
|
数据库
【YashanDB知识库】数据库用户所拥有的权限查询
【YashanDB知识库】数据库用户所拥有的权限查询
|
9月前
|
存储 运维 监控
百万指标,秒级查询,零宕机——时序数据库 TDengine 在 AIOps 中的硬核实战
本篇文章详细讲述了七云团队在运维平台中如何利用 TDengine 解决海量时序数据存储与查询的实际业务需求。内容涵盖了从数据库选型、方案落地到业务挑战及解决办法的完整过程,特别是分享了升级 TDengine 3.x 时的实战经验,给到有需要的小伙伴参考阅读。
344 1
|
5月前
|
NoSQL MongoDB 数据库
数据库数据恢复—MongoDB数据库数据恢复案例
MongoDB数据库数据恢复环境: 一台操作系统为Windows Server的虚拟机上部署MongoDB数据库。 MongoDB数据库故障: 工作人员在MongoDB服务仍然开启的情况下将MongoDB数据库文件拷贝到其他分区,数据复制完成后将MongoDB数据库原先所在的分区进行了格式化操作。 结果发现拷贝过去的数据无法使用。管理员又将数据拷贝回原始分区,MongoDB服务仍然无法使用,报错“Windows无法启动MongoDB服务(位于 本地计算机 上)错误1067:进程意外终止。”
|
5月前
|
缓存 NoSQL Linux
在CentOS 7系统中彻底移除MongoDB数据库的步骤
以上步骤完成后,MongoDB应该会从您的CentOS 7系统中被彻底移除。在执行上述操作前,请确保已经备份好所有重要数据以防丢失。这些步骤操作需要一些基本的Linux系统管理知识,若您对某一步骤不是非常清楚,请先进行必要的学习或咨询专业人士。在执行系统级操作时,推荐在实施前创建系统快照或备份,以便在出现问题时能够恢复到原先的状态。
443 79
|
5月前
|
存储 NoSQL MongoDB
MongoDB数据库详解-针对大型分布式项目采用的原因以及基础原理和发展-卓伊凡|贝贝|莉莉
MongoDB数据库详解-针对大型分布式项目采用的原因以及基础原理和发展-卓伊凡|贝贝|莉莉
278 8
MongoDB数据库详解-针对大型分布式项目采用的原因以及基础原理和发展-卓伊凡|贝贝|莉莉

推荐镜像

更多