1. <?php
  2. /**
  3. *
  4. * @link        https://github.com/thendfeel/TmongoDB
  5. * @example
  6. * @copyright
  7. * @site        http://www.uacool.com
  8. * @created     2013-12-13
  9. *
  10. * Manual
  11. * http://us2.php.net/mongo
  12. * 针对阿里云MongoDB数据库
  13. * SQL to Mongo Mapping Chart
  14. * http://us2.php.net/manual/en/mongo.sqltomongo.php
  15. * 单例模式(只针对相同的config)
  16. */
  17. class TmongoDB
  18. {
  19. protected $_db = 'test';
  20. protected $_collection = 'user';
  21. protected $_validate = array();
  22. protected static $_mongoObj = array();
  23. private $_exeResult = null;
  24. protected $_sql = array();
  25. protected $_mongo = null;
  26. const CONNECT_DB = 'admin'; // 连接数据库,默认为admin
  27. /**
  28. * Config For MongDB
  29. *
  30. * @var array
  31. */
  32. protected $_config = array(
  33. 'mongo_seed1' => 'localhost',
  34. 'mongo_seed2' => '',
  35. 'mongo_replname' => '',
  36. 'mongo_user' => NULL,
  37. 'mongo_pwd' => NULL
  38. );
  39. public function __construct($config,$db, $collection)
  40. {
  41. foreach ($this->_config as $k => $v) {
  42. if(isset($config[$k])){
  43. $this->_config[$k] = $config[$k];
  44. } else {
  45. E('mongoDB数据库连接,请传递'.$k);
  46. }
  47. }
  48. $this->_db = $db;
  49. $this->_collection = $collection;
  50. $this->init();
  51. }
  52. public function getMongo()
  53. {
  54. return $this->_mongo;
  55. }
  56. /**
  57. * Init The Class
  58. * 对于相同的配置只初始化一次
  59. * @param string $db
  60. * @param string $collection
  61. */
  62. public function init()
  63. {
  64. $config = $this->_config;
  65. ksort($config);
  66. $encryptStr = '';
  67. foreach ($config as $k => $v) {
  68. $encryptStr .= ($k.$v);
  69. }
  70. $key = md5($encryptStr);
  71. if (!self::$_mongoObj[$key]) {
  72. /*$conStr = "mongodb://";
  73. if ($config['user'] && $config['password']) {
  74. $conStr .= "{$config['user']}:{$config['password']}@";
  75. }
  76. $conStr .= "{$config['host']}:{$config['port']}";
  77. $_mongoDB = new \Mongo($conStr, array(
  78. "connect" => false
  79. ));*/
  80. $demo_uri = 'mongodb://' . $config['mongo_user'] . ':' . $config['mongo_pwd'] . '@' .
  81. $config['mongo_seed1'] . ',' . $config['mongo_seed2'] . '/' . self::CONNECT_DB . '?replicaSet=' . $config['mongo_replname'];
  82. $manager = new \MongoDB\Driver\Manager($demo_uri);
  83. self::$_mongoObj[$key] = $this->_mongo = $manager;
  84. /*if ($db && $collection) {
  85. $this->_mongoDB = $_mongoDB->selectCollection($db, $collection);
  86. } else {
  87. $this->_mongoDB = $_mongoDB->selectCollection($this->_db,$this->_collection);
  88. }*/
  89. } else {
  90. $this->_mongo = self::$_mongoObj[$key];
  91. }
  92. }
  93. /**
  94. * Set Db & Collection
  95. * 重新设置数据库和数据表
  96. * @param string $db
  97. * @param string $collection
  98. */
  99. public function setDb($db = NULL, $collection = NULL)
  100. {
  101. if ($db) {
  102. $this->_db = $db;
  103. //$this->_mongoDB = NULL;
  104. //$this->_mongoDB = $this->_mongoObj->selectCollection($this->_db,$this->_collection);
  105. }
  106. if ($collection) {
  107. $this->_collection = $collection;
  108. }
  109. return $this;
  110. }
  111. /**
  112. * Set Collection
  113. * 重新设置数据表
  114. * @param string $collection
  115. */
  116. public function setCollection($collection = NULL)
  117. {
  118. if ($collection) {
  119. $this->_collection = $collection;
  120. //$this->_mongoDB = NULL;
  121. //$this->_mongoDB = $this->_mongoObj->selectCollection($this->_db,$collection);
  122. }
  123. return $this;
  124. }
  125. /**
  126. * 获取指定条件下的集合里的数据数量,默认使用_id主键字段
  127. */
  128. public function count($argv = array(),$fields = '_id')
  129. {
  130. $result = $this->find($argv,$fields);
  131. if ($result) {
  132. return count($result);
  133. } else {
  134. return 0;
  135. }
  136. }
  137. /**
  138. * Fetch From Mongodb
  139. *
  140. * @param array $argv
  141. * @param number $skip
  142. * @param number $limit
  143. * @param array $sort
  144. * @return Ambigous <multitype:, multitype:>|boolean
  145. */
  146. public function find($argv = array(),$fields = array(),$sort = array(),$skip = 0, $limit = 0)
  147. {
  148. /*$argv = $this->validate($argv);
  149. if ($argv) {
  150. $result = $this->_mongoDB->find($argv)
  151. ->skip($skip)
  152. ->limit($limit)
  153. ->sort($sort);
  154. return self::toArray($result);
  155. }*/
  156. $options = array();
  157. if ($skip) {
  158. $options['skip'] = $skip;
  159. }
  160. if ($limit) {
  161. $options['limit'] = $limit;
  162. }
  163. if ($sort) {
  164. $options['sort'] = $sort;
  165. }
  166. if ($fields) {
  167. if (is_string($fields)) {
  168. $fields = explode(',', $fields);
  169. }
  170. foreach ($fields as $v) {
  171. $options['projection'][$v] = 1;
  172. }
  173. }
  174. $query = new \MongoDB\Driver\Query($argv, $options);
  175. $cursor = $this->_mongo->executeQuery($this->_db.'.'.$this->_collection, $query);
  176. return $cursor->toArray();
  177. }
  178. /**
  179. * 执行命令
  180. */
  181. public function runCommand($command = array())
  182. {
  183. if (!$command) {
  184. return false;
  185. }
  186. $commandObj = new \MongoDB\Driver\Command($command);
  187. try {
  188. $cursor = $this->_mongo->executeCommand($this->_db, $commandObj);
  189. $response = $cursor->toArray();
  190. } catch(\MongoDB\Driver\Exception $e) {
  191. echo 'Mongo的runCommand异常:',$e->getMessage();
  192. exit;
  193. }
  194. if (count($response) > 1) {
  195. return $response;
  196. } else {
  197. return $response[0];
  198. }
  199. }
  200. /**
  201. * Fetch By MongoId
  202. *
  203. * @param string $_id
  204. * @return Ambigous <Ambigous, boolean, multitype:>
  205. */
  206. public function findById($_id = '',$fields = array())
  207. {
  208. if (is_string($_id)) {
  209. return $this->findOne(array('_id' => new \MongoDB\BSON\ObjectID($_id)),$fields);
  210. }
  211. }
  212. /**
  213. * Fetch One From MongoDB
  214. *
  215. * @param array $argv
  216. * @param array $fields
  217. * @return multitype: boolean
  218. */
  219. public function findOne($argv = array(),$fields = array(),$sort = array())
  220. {
  221. $result = $this->find($argv,$fields,$sort,0,1);
  222. if ($result) {
  223. return $result[0];
  224. } else {
  225. return NULL;
  226. }
  227. //return $this->cleanId($this->_mongoDB->findOne($argv, $fields));
  228. }
  229. /**
  230. * Update MongoDB By Id
  231. * 通过主键ID更新
  232. * @param string $_id
  233. * @param array $newData
  234. */
  235. public function updateById($_id, $set = array())
  236. {
  237. return $this->updateStatement(array('_id' => new \MongoDB\BSON\ObjectID($_id)), array('$set'=>$set))->execute()->getModifiedCount();
  238. }
  239. /**
  240. * 执行添加,删除,更新 All From Mongodb,执行多个语句
  241. * $obj->deleteStatement(array('name'=>'1'))->deleteStatement(array('id'=>1))->remove();
  242. * @param array $argv
  243. */
  244. public function execute()
  245. {
  246. if (!$this->_sql) {
  247. return NULL;
  248. }
  249. $bulk = new \MongoDB\Driver\BulkWrite;
  250. foreach ($this->_sql as $val) {
  251. switch ($val['type']) {
  252. case 'delete':
  253. $bulk->delete($val['sql'],$val['limit']);
  254. break;
  255. case 'insert':
  256. $bulk->insert($val['document']);
  257. break;
  258. case 'update':
  259. $bulk->update($val['filter'],$val['set'],$val['options']);
  260. break;
  261. }
  262. }
  263. $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
  264. try {
  265. $this->_exeResult = $this->_mongo->executeBulkWrite($this->_db.'.'.$this->_collection, $bulk, $writeConcern);
  266. } catch(\MongoDB\Driver\Exception\WriteException $e) {
  267. echo 'MongoDB扩展写入异常:';
  268. $writeResult = $e->getWriteResult();
  269. if ($writeConcernError = $writeResult->getWriteConcernError()) {
  270. echo $writeConcernError[0]->getMessage(),'<br />';
  271. }
  272. if ($writeErrors = $writeResult->getWriteErrors()) {
  273. echo $writeErrors[0]->getMessage();
  274. }
  275. exit();
  276. } catch (\MongoDB\Driver\Exception\InvalidArgumentException $e) {
  277. exit('MongoDB扩展传入参数异常:'.$e->getMessage());
  278. } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
  279. exit('MongoDB扩展运行异常:'.$e->getMessage());
  280. } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
  281. exit('MongoDB扩展运行超时异常:'.$e->getMessage());
  282. } catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $e) {
  283. exit('MongoDB扩展连接超时异常:'.$e->getMessage());
  284. } catch (\Exception $e) {
  285. exit('系统异常:'.$e->getMessage());
  286. }
  287. return $this;
  288. }
  289. /**
  290. * 获取删除的行数
  291. */
  292. public function getDeletedCount()
  293. {
  294. if ($this->_exeResult) {
  295. return $this->_exeResult->getDeletedCount();
  296. } else {
  297. return 0;
  298. }
  299. }
  300. /**
  301. * 获取实际更新的行数
  302. */
  303. public function getModifiedCount()
  304. {
  305. if ($this->_exeResult) {
  306. return $this->_exeResult->getModifiedCount();
  307. } else {
  308. return 0;
  309. }
  310. }
  311. /**
  312. * 一次最多插入9万条以下.耗时
  313. * 获取实际插入的行数
  314. */
  315. public function getInsertedCount()
  316. {
  317. if ($this->_exeResult) {
  318. return $this->_exeResult->getInsertedCount();
  319. } else {
  320. return 0;
  321. }
  322. }
  323. /**
  324. * 获取实际匹配的行数
  325. */
  326. public function getMatchedCount()
  327. {
  328. if ($this->_exeResult) {
  329. return $this->_exeResult->getMatchedCount();
  330. } else {
  331. return 0;
  332. }
  333. }
  334. /**
  335. * 获取实际更新失败然后新插入的行数
  336. *
  337. */
  338. public function getUpsertedCount()
  339. {
  340. if ($this->_exeResult) {
  341. return $this->_exeResult->getUpsertedCount();
  342. } else {
  343. return 0;
  344. }
  345. }
  346. /**
  347. * 获取实际更新失败然后新插入的ID列表
  348. */
  349. public function getUpsertedIds()
  350. {
  351. if ($this->_exeResult) {
  352. return $this->_exeResult->getUpsertedIds();
  353. } else {
  354. return 0;
  355. }
  356. }
  357. /**
  358. * delete子句
  359. * @param $delete 为删除过滤条件,为数组形式
  360. */
  361. public function deleteStatement($delete,$limit = 0)
  362. {
  363. $this->_sql[] = array('type'=>'delete','sql'=>$delete,'limit'=>array('limit'=>$limit));
  364. return $this;
  365. }
  366. /**
  367. * insert子句
  368. * @param $batch 批量插入数据
  369. */
  370. public function insertStatement($insert,$batch = false)
  371. {
  372. if ($batch) {
  373. if (is_array($insert) && $insert) {
  374. foreach ($insert as $val) {
  375. $this->_sql[] = array('type'=>'insert','document'=>$val);
  376. }
  377. }
  378. } else {
  379. $this->_sql[] = array('type'=>'insert','document'=>$insert);
  380. }
  381. return $this;
  382. }
  383. /**
  384. * update子句
  385. * @param option multi 为true则更新全部符合条件的文档,否则只更新一个符合条件的文档
  386. *              upsert 为true则当没有符合条件的文档时将更新过后的数据插入到集合中
  387. * 参考连接:http://blog.csdn.net/qq1355541448/article/details/9082225
  388. * 第二个参数有以下的做法:
  389. *  修改更新
  390. *      使用set关键字: $set:让某节点等于给定值 ,字段不变,内容变了
  391. *  替换更新:
  392. *      第一个参数$where=array(‘column_name’=>’col709′),第二个参数:$newdata=array(‘column_exp’=>’HHHHHHHHH’,'column_fid’=>123);
  393. *      那么指定的column_name字段将会替换成成column_exp(=HHHHHHHHH)和column_fid(123)
  394. *  自动累加或自动累减
  395. *      array(‘$set’=>$newdata,’$inc’=>array(’91u’=>-5),第二个参数,在找到的91u字段的参数会自动在原值减5
  396. *  删除指定字段
  397. *      $where=array(‘column_name’=>’col685′);
  398. *      $result=$collection->update($where,array(‘$unset’=>’column_exp’));column_exp字段将会被删除
  399. * 参考文档:https://docs.mongodb.org/manual/reference/operator/update/
  400. */
  401. public function updateStatement($filter,$set,$options = array('multi' => true, 'upsert' => false))
  402. {
  403. $this->_sql[] = array('type'=>'update','filter'=>$filter,'set'=>$set,'options'=>$options);
  404. return $this;
  405. }
  406. /**
  407. * Remove By Id From Mongodb
  408. *
  409. * @param string $_id
  410. * @return Ambigous <boolean, multitype:>
  411. */
  412. public function removeById($_id)
  413. {
  414. return $this->deleteStatement(array('_id' => new \MongoDB\BSON\ObjectID($_id)))->execute()->getDeletedCount();
  415. }
  416. /**
  417. * Remove One From Mongodb
  418. *
  419. * @param array $argv
  420. */
  421. public function removeOne($argv = array())
  422. {
  423. return $this->deleteStatement($argv,1)->execute()->getDeletedCount();
  424. }
  425. /**
  426. * Remove Field From MongoDB
  427. *
  428. * @param string $_id
  429. * @param array $field
  430. */
  431. //  public function removeFieldById($_id, $field = array())
  432. //  {
  433. //      return $this->updateStatement(array('_id' => new \MongoDB\BSON\ObjectID($_id)), array('$unset' => $unSetfield));
  434. //  }
  435. /**
  436. * Validate Data Callbak Function 没有用到的函数
  437. *
  438. * @param array $argv
  439. */
  440. private function validate($data)
  441. {
  442. if ($this->_validate) {
  443. foreach ($this->_validate as $arg => $validate) {
  444. if (is_array($data) && array_key_exists(strval($arg), $data)) {
  445. foreach ($validate as $key => $value) {
  446. switch (strtolower($key)) {
  447. case 'type':
  448. if ($value == 'int') {
  449. $data[$arg] = (int) $data[$arg];
  450. } elseif ($value == 'string') {
  451. $data[$arg] = (string) $data[$arg];
  452. } elseif ($value == 'bool') {
  453. $data[$arg] = (bool) $data[$arg];
  454. } elseif ($value == 'float') {
  455. $data[$arg] = (float) $data[$arg];
  456. } elseif ($value == 'array') {
  457. $data[$arg] = (array) $data[$arg];
  458. }
  459. break;
  460. case 'min':
  461. if (strlen($data[$arg]) < $value) {
  462. exit('Error: The length of ' . $arg . ' is not matched');
  463. }
  464. break;
  465. case 'max':
  466. if (strlen($data[$arg]) > $value) {
  467. exit('Error: The length of ' . $arg . ' is not matched');
  468. }
  469. break;
  470. case 'func':
  471. $call = preg_split('/[\:]+|\-\>/i', $value);
  472. if (count($call) == 1) {
  473. $data[$arg] = call_user_func($call['0'], $data[$arg]);
  474. } else {
  475. $data[$arg] = call_user_func_array(array($call['0'],$call['1']), array($data[$arg]));
  476. }
  477. break;
  478. }
  479. }
  480. }
  481. }
  482. }
  483. return $data;
  484. }
  485. /**
  486. * mongdodb服务器的相关信息
  487. */
  488. public function buildInfo()
  489. {
  490. return $this->runCommand(array('buildinfo'=>1));
  491. }
  492. /**
  493. * 返回指定集合的统计信息,包括数据大小、已分配的存储空间和索引的大小。
  494. */
  495. public function collStats($collection = '')
  496. {
  497. if (!$collection) {
  498. $collection = $this->_collection;
  499. if (!$collection) {
  500. return NULL;
  501. }
  502. }
  503. return $this->runCommand(array('collstats'=>$collection));
  504. }
  505. /**
  506. * 列出指定集合中满足查询条件的文档的指定键的所有不同值
  507. */
  508. public function distinct($field,$filter = array(),$collection = '')
  509. {
  510. if (!$collection) {
  511. $collection = $this->_collection;
  512. if (!$collection) {
  513. return NULL;
  514. }
  515. }
  516. return false;
  517. return $this->runCommand(array('key'=>$field,'query'=>$filter,'distinct'=>$collection));
  518. }
  519. /**
  520. * 删除集合的所有数据
  521. */
  522. public function drop($collection = '')
  523. {
  524. if (!$collection) {
  525. $collection = $this->_collection;
  526. if (!$collection) {
  527. return NULL;
  528. }
  529. }
  530. return $this->runCommand(array('drop'=>$collection));
  531. }
  532. /**
  533. * 删除当前数据库中的所有数据
  534. */
  535. public function dropDatabase()
  536. {
  537. return $this->runCommand(array('dropdatabase'=>1));
  538. }
  539. /**
  540. * 删除集合里面名称为name的索引,如果名称为"*",则删除全部索引。
  541. */
  542. public function dropIndexes($index = '*',$collection = '')
  543. {
  544. if (!$collection) {
  545. $collection = $this->_collection;
  546. if (!$collection) {
  547. return NULL;
  548. }
  549. }
  550. return $this->runCommand(array('dropIndexes'=>$collection,'index' => $index));
  551. }
  552. //  /**
  553. //   * 创建索引
  554. //   */
  555. //  public function createIndexes($index,$collection = '')
  556. //  {
  557. //      if (!$collection) {
  558. //          $collection = $this->_collection;
  559. //          if (!$collection) {
  560. //              return NULL;
  561. //          }
  562. //      }
  563. //      return $this->runCommand(array('createIndexes'=>array('create'=>$collection),'index' => array('name'=>$index)));
  564. //  }
  565. /**
  566. * 列出某个集合下所有的索引
  567. */
  568. public function listIndexes($collection = '')
  569. {
  570. if (!$collection) {
  571. $collection = $this->_collection;
  572. if (!$collection) {
  573. return NULL;
  574. }
  575. }
  576. return $this->runCommand(array('listIndexes'=>$collection));
  577. }
  578. /**
  579. * 查找并修改
  580. */
  581. public function findAndModify($update = array(),$filter = array(),$collection = '')
  582. {
  583. if (!$collection) {
  584. $collection = $this->_collection;
  585. if (!$collection) {
  586. return NULL;
  587. }
  588. }
  589. return $this->runCommand(array('findAndModify'=>$collection,'query' => $filter,'update'=>$update));
  590. }
  591. /**
  592. * 查看对本集合执行的最后一次操作的错误信息或者其它状态信息。在w台服务器复制集合的最后操作之前,这个命令会阻塞
  593. */
  594. public function getLastError()
  595. {
  596. return $this->runCommand(array('getLastError'=>1));
  597. }
  598. /**
  599. * 检查本服务器是主服务器还是从服务器
  600. */
  601. public function isMaster()
  602. {
  603. return $this->runCommand(array('ismaster'=>1));
  604. }
  605. /**
  606. * 返回所有可以在服务器上运行的命令及相关信息。
  607. */
  608. public function listCommands()
  609. {
  610. return $this->runCommand(array('listCommands'=>1));
  611. }
  612. /**
  613. * 管理专用命令,列出服务器上所有的数据库
  614. */
  615. public function listDatabases()
  616. {
  617. return $this->setDb('admin')->runCommand(array('listDatabases'=>1));
  618. }
  619. /**
  620. * 检查服务器链接是否正常。即便服务器上锁了,这条命令也会立刻返回
  621. */
  622. public function ping()
  623. {
  624. return $this->runCommand(array('ping'=>1));
  625. }
  626. /**
  627. * 将集合a重命名为b,其中a和b都必须是完整的集合命名空间(例如"test.foo"代表test数据库中的foo集合)
  628. * @param dropTarget Optional. If true, mongod will drop the target of renameCollection prior to renaming the collection. The default value is false.
  629. * 用法. $fromCollection = 'test.demo' , $toCollection = 'test.demo1' ,一定要加数据库前缀
  630. */
  631. public function renameCollection($fromCollection,$toCollection,$dropTarget = false)
  632. {
  633. if (!$fromCollection || !$toCollection) {
  634. return false;
  635. }
  636. return $this->setDb('admin')->runCommand(array('renameCollection'=>$fromCollection,'to'=>$toCollection,'dropTarget'=>$dropTarget));
  637. }
  638. /**
  639. * 修复并压缩当前数据库,这个操作可能非常耗时。
  640. */
  641. public function repairDatabase()
  642. {
  643. return $this->setDb('admin')->runCommand(array('repairdatabase'=>1));
  644. }
  645. /**
  646. * 返回这台服务器的管理统计信息。
  647. */
  648. public function serverStatus()
  649. {
  650. return $this->runCommand(array('serverStatus'=>1));
  651. }
  652. /**
  653. * 创建集合
  654. * $options = array('autoIndexId','capped','size','max','flags');
  655. */
  656. public function createCollection($collection,$options = array())
  657. {
  658. $options['create'] = $collection;
  659. return $this->runCommand($options);
  660. }
  661. /**
  662. * 删除集合
  663. */
  664. public function dropCollection($collection)
  665. {
  666. if (!$collection) {
  667. return NULL;
  668. }
  669. return $this->runCommand(array('drop'=>$collection));
  670. }
  671. }

部分用法如下:

[php] view plain copy
  1. $config = array(
  2. 'mongo_seed1' => C('mongo_seed1'),
  3. 'mongo_seed2' => C('mongo_seed2'),
  4. 'mongo_replname' => C('mongo_replname'),
  5. 'mongo_user' => C('mongo_user'),
  6. 'mongo_pwd' => C('mongo_pwd')
  7. );
  8. $mongoObj = new \Org\Util\TmongoDB($config,'demo','test');
  9. $insert = array(
  10. array(
  11. 'name'=> '走令敏',
  12. 'age'=> 24,
  13. 'address' => '江西省赣州市',
  14. 'gender' => '男',
  15. 'salary' => 5500
  16. ),
  17. array(
  18. 'name'=> '皇兄文',
  19. 'age'=> 24,
  20. 'address' => '江西省抚州市',
  21. 'gender' => '男',
  22. 'salary' => 6000
  23. ),
  24. array(
  25. 'name'=> '周李菲',
  26. 'age'=> 23,
  27. 'address' => '江西省上饶市',
  28. 'gender' => '男',
  29. 'salary' => 5000
  30. ),
  31. array(
  32. 'name'=> '主力科',
  33. 'age'=> 25,
  34. 'address' => '江西省上饶市',
  35. 'gender' => '男',
  36. 'salary' => 1000
  37. ),
  38. array(
  39. 'name'=> '夜舟',
  40. 'age'=> 25,
  41. 'address' => '江西省上饶市',
  42. 'gender' => '男',
  43. 'salary' => 7000
  44. ),
  45. array(
  46. 'name'=> '周倩倩',
  47. 'age'=> 23,
  48. 'address' => '江西省上饶市',
  49. 'gender' => '女',
  50. 'salary' => 7000
  51. ),
  52. array(
  53. 'name'=> '网点保',
  54. 'age'=> 22,
  55. 'address' => '河南省鹤壁市',
  56. 'gender' => '男',
  57. 'salary' => 10000
  58. ),
  59. array(
  60. 'name'=> '舒玉婷',
  61. 'age'=> 24,
  62. 'address' => '江西省上饶市',
  63. 'gender' => '女',
  64. 'salary' => 6000
  65. ),
  66. array(
  67. 'name'=> '少见波',
  68. 'age'=> 27,
  69. 'address' => '辽宁省吉林市',
  70. 'gender' => '男',
  71. 'salary' => 20000
  72. ),
  73. array(
  74. 'name'=> '李存平',
  75. 'age'=> 25,
  76. 'address' => '江西省吉安市',
  77. 'gender' => '男',
  78. 'salary' => 6000
  79. )
  80. );
  81. $arr = array();
  82. for ($i = 0;$i < 10;++$i) {
  83. for ($j = 0;$j < 10;++$j) {
  84. $key = $i*10 + $j;
  85. $arr[$key] = $insert[$j];
  86. $arr[$key]['num'] = $key;
  87. $arr[$key]['_id'] = new \MongoDB\BSon\ObjectID;
  88. }
  89. }
  90. $starttime = microtime(true);
  91. $result = $mongoObj->insertStatement($arr,true)->execute()->getInsertedCount();;
  92. $endtime = microtime(true);
  93. echo '执行时间:',($endtime - $starttime),'秒<br />';
  94. echo $result;
  95. echo 'ping';
  96. // 查询所有的记录
  97. $result = $mongoObj->runCommand(array('ping'=>1));
  98. dump($result);
  99. echo '<br/>,getLastError';
  100. $error = $mongoObj->getLastError();
  101. dump($error);
  102. $result = $mongoObj->buildInfo();
  103. echo '<br/>,buildInfo';
  104. dump($result);
  105. $result = $mongoObj->collStats('test');
  106. echo '<br/>,collStats';
  107. dump($result);
  108. $result = $mongoObj->distinct('salary',array('num'=>array('$gt'=>20)));
  109. echo '<br />,distinct';
  110. dump($result);
  111. $result = $mongoObj->isMaster();
  112. echo '<br />,isMaster';
  113. dump($result);
  114. $result = $mongoObj->listCommands();
  115. echo '<br/>,listCommands';
  116. dump($result);
  117. $result = $mongoObj->listDatabases();
  118. echo '<br/>,listDatabases';
  119. dump($result);
  120. $result = $mongoObj->serverStatus();
  121. echo '<br/>,serverStatus';
  122. dump($result);
  123. $result = $mongoObj->renameCollection('demo.hello', 'demo.hello123');
  124. echo '<br/>,renameCollection';
  125. dump($result);
  126. $result = $mongoObj->createCollection('ceshi');
  127. echo '<br/>,createCollection';
  128. dump($result);
  129. $result = $mongoObj->dropCollection('demo1');
  130. echo '<br />,dropCollection';
  131. dump($result);

来源:http://blog.csdn.net/zhulike2011/article/details/50422391

MongoDB for PHP扩展操作类相关推荐

  1. Spring整合Mongodb,Maven的依赖,Spring配置,MongoDB的公共操作类,使用SpringMVC的Controller进行测试并返回结果的案例

    在和Spring和MongoDB进行整合的时候需要如下三个jar,分别是: spring-data-commons spring-data-mongodb mongo-java-driver 下面讲解 ...

  2. MongoDB PHP数据库查询类

    Java代码   <?php /*** Mongodb类** examples: * $mongo = new HMongodb("127.0.0.1:11223"); *  ...

  3. PHP操作Mongodb API 及使用类 封装好的MongoDB操作类

    来源:http://www.itokit.com/2012/0427/73656.html <?php /*** Mongodb类** examples: * $mongo = new HMon ...

  4. java MongoDB直接存pojo类

    Pojo实体 UserFaceCollection.java import lombok.Data; import java.io.Serializable; import java.util.Dat ...

  5. mongoDB数据库操作工具库

    /* Mongodb的数据库工具类 */ var client = require('mongodb').MongoClient;function MongoUtil() { this.url=&qu ...

  6. 数据数字mongodb 模糊查询以及$type使用

    本文是一篇关于数据数字的帖子 近最有一监控业务,由于数据采集到非数字内容,致导监控图表法无常正表现,所以要找出这部分数据,停止删除,然后开辟员从头源改正插入数据库的数据,不再发生非数字内容. 上面举一 ...

  7. 在JAVA中使用MongoDB

    2019独角兽企业重金招聘Python工程师标准>>> 首先,下载mongdb对JAVA的支持,点击这里下载驱动包,这里博主下载的是2.10.1版. mongdb版本为2.4.9 在 ...

  8. spring boot多数据源配置(mysql,redis,mongodb)实战

    使用Spring Boot Starter提升效率 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfi ...

  9. boot jndi数据源 spring_spring boot多数据源配置(mysql,redis,mongodb)实战

    使用Spring Boot Starter提升效率 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfi ...

最新文章

  1. div+css中命名规范
  2. DroidPilot 测试脚本详解 (一)
  3. html菜单浮动,浮动菜单,可实现上下滚动的效果
  4. python库怎么学啊最好_最常用的几个python库--学习引导
  5. 第一节:从面向对象思想(oo)开发、接口、抽象类以及二者比较
  6. Qt 模态对话框不模态的问题
  7. java静态方法和非静态方法的区别_史上最全阿里 Java 面试题总结
  8. Javascript特效:照片墙
  9. JAVA变量直接可以相加不,Java学习第一天
  10. 电信iptv机顶盒破解方法大全(图文教程)
  11. protel 99se 层次原理图的切换
  12. java实习每周总结
  13. 【FastDFS】分布式文件系统FastDFS之FastDHT文件去重
  14. macOS Big Sur 11.7.2 (20G1020) 正式版 ISO、PKG、DMG、IPSW 下载
  15. 前端网站连接MySQL数据库
  16. 利用命令行实现图片转换等操作--ImageMagick
  17. 数据分析需要掌握的知识(2)
  18. 初始C++ - auto关键字与内联函数
  19. SVN 在Eclipse中使用
  20. GUI编程--PyQt5--QWidget2

热门文章

  1. 图片变成暗灰色的html,暗灰色的圆形按钮.html
  2. MySQL索引介绍,普通索引,全文索引,空间索引,多列索引使用原则,建立索引常用的规则
  3. Rotation Rose各部分的名称
  4. 将虚拟机的版本改为1.6的方法
  5. BeautifulSoup children descendants对比
  6. 深度学习论文翻译--Deep Residual Learning for Image Recognition
  7. 算法: 把字字符串转化为整数;
  8. iOS中去除 Warning警告
  9. Java GC垃圾回收机制
  10. Tesseract图形识别软件的安装