您尚未登录,请登录后浏览更多内容! 登录 | 立即注册

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 15962|回复: 0
打印 上一主题 下一主题

[php学习资料] 升级PHP7操作MongoDB

[复制链接]
跳转到指定楼层
楼主
发表于 2019-3-19 14:24:22 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。
详情请见官方手册:http://php.net/manual/zh/book...
但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。
详情也可参见官方手册:http://php.net/manual/zh/set....
在这种情况之下,MongoDB 官方忍不住了,为了方便使用,增加市场占有率,推出了基于MongoDB 扩展的库:https://github.com/mongodb/mo...
该库的详细文档见:https://docs.mongodb.com/php-...
MongoDB 驱动
如果使用原驱动的话,大致语法如下:
  1. <?php* q2 ~9 l& k& _# b! \

  2. 8 V7 b5 x5 H) q6 \7 q3 u$ d  G
  3. use MongoDB\Driver\Manager;) D! G' ]( i' J* f6 N4 g
  4. use MongoDB\Driver\BulkWrite;' u0 F% v" @5 h  G! ]3 I  h/ [4 O
  5. use MongoDB\Driver\WriteConcern;
    # K) C( n' G2 ?9 c( Z5 H" ]+ ?
  6. use MongoDB\Driver\Query;
    ( q2 G) O2 G+ U+ b& t& o
  7. use MongoDB\Driver\Command;
    5 t6 F# X. v' l0 ?
  8. # O# u- e% q8 D; V
  9. class MongoDb {4 d0 V0 b# u% y, G3 n

  10. $ T+ B- V( b* p) Q
  11.     protected $mongodb;
    ) B' k7 l5 k: ?' C1 y* F+ {2 Y
  12.     protected $database;
    2 |$ @4 i% z3 u! K) E: T+ W* ^. J3 `  r: u
  13.     protected $collection;
      f2 b0 U. R0 A7 J2 k
  14.     protected $bulk;: n5 e* g6 F/ o- |1 Y# d, m2 T
  15.     protected $writeConcern;' _. j, q4 A4 ^5 G0 f/ C: z
  16.     protected $defaultConfig2 Z5 e1 @/ }; e+ ~7 Z: I
  17.         = [% y5 J% [. x# |( B' p& D$ [
  18.             'hostname' => 'localhost',8 `2 H0 H* k1 |8 y6 K. f" P- m3 y1 M
  19.             'port' => '27017',
    & k$ {3 |' X7 s- Q+ f
  20.             'username' => '',$ u: F$ y8 u7 C7 s7 l! U
  21.             'password' => '',, X# m8 N% [5 d2 u. E+ J
  22.             'database' => 'test'
    6 `1 P9 d6 u7 z; ^
  23.         ];' p" e& k+ B& ]& M- S1 g

  24. 1 g  S1 q) x* g6 J
  25.     public function __construct($config) {, `5 c" K+ b1 D0 W
  26.         $config = array_merge($this->defaultConfig, $config);" P+ |% C% Z# R( r" t
  27.         $mongoServer = "mongodb://";( `0 R% e. E! A/ H9 T% @8 {1 ?
  28.         if ($config['username']) {
    ) j" F' e: |4 |7 u' \
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    , y7 J# g- [( `, j& }* i
  30.         }
    2 d% c! e+ c$ d+ d. V6 p! \
  31.         $mongoServer .= $config['hostname'];
    0 w, J; k2 s4 L, O  p, Y
  32.         if ($config['port']) {( |9 s2 r$ e- v- A/ ?8 y/ @
  33.             $mongoServer .= ':' . $config['port'];) u! O/ t/ r6 y+ ?7 z& t- }
  34.         }
    8 D* Q5 {8 _# ]$ u: z6 V
  35.         $mongoServer .= '/' . $config['database'];
    5 k3 {4 ~7 X; L* S. F1 p. b: b+ T

  36. $ M' d% d. _/ h/ p3 l* S5 W9 J
  37.         $this->mongodb = new Manager($mongoServer);. r, Z( m8 H4 H
  38.         $this->database = $config['database'];
    ' V; U! v( R7 q' R( ?( d( r
  39.         $this->collection = $config['collection'];
    5 _- ]- \0 j5 p* P
  40.         $this->bulk = new BulkWrite();
    9 }2 F* u- f. W) E3 y
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    , C1 J- p) G4 b1 B* `
  42.     }
    - F& g8 C' K. x! D: Q

  43. * n# i1 Q, L/ U  Q3 R4 s; T$ @3 J
  44.     public function query($where = [], $option = []) {
    3 q: O4 {, ]9 \  V
  45.         $query = new Query($where, $option);
    $ r, D$ `+ G, ?5 R  E& w
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    / x* x* {' u% b7 P8 K
  47. 1 ~& x- S9 R/ M8 |
  48.         return json_encode($result);+ N$ d/ _/ n. F5 o: V# y
  49.     }
    3 w: K. z9 N* ?4 j( _  z2 G
  50. 6 X3 E( o, ?; X8 {  i
  51.     public function count($where = []) {9 x. A: z3 b3 _- q
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);5 H1 M5 A' f6 ]% \
  53.         $result = $this->mongodb->executeCommand($this->database, $command);; M0 r, l9 v! Z- J( w6 E) v( g! m
  54.         $res = $result->toArray();2 E, y, w4 d0 @* X9 c/ o
  55.         $count = 0;
    ! B) `% }" l  {7 |  h+ P
  56.         if ($res) {
    5 k! d# F  U; ~  p" J/ Z
  57.             $count = $res[0]->n;/ X* M6 h; N1 I" t  t1 N
  58.         }
    . f$ N% j  B% }& I; [6 O

  59. ( k9 z, x2 c3 f1 R8 [+ N
  60.         return $count;
    " m7 `" T- j7 `, ?4 D7 @
  61.     }* F; M* h( ]- a& t7 W
  62. ! B  d7 C' T' ~0 w( K2 i
  63.     public function update($where = [], $update = [], $upsert = false) {
    ( P! s1 V8 f) G8 Q* |0 I
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);% A8 Z" c( q3 o$ Y$ V+ i
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    3 Z3 F. w) h% c* T
  66. ' V( q7 _- l6 d, I- a
  67.         return $result->getModifiedCount();
    , C" k8 q3 R- p( J, y. l* @  x
  68.     }2 k8 E3 t  F' Q2 @! U, O! W$ f

  69. 1 f% G. \2 J. ^( L* p2 Y. c
  70.     public function insert($data = []) {5 N0 K# @; w" D+ ~  R$ u6 ~4 \# @8 N
  71.         $this->bulk->insert($data);+ H; }$ f) y. W9 l" S. A
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ! ]4 q! l0 B  {& I; {

  73. # p9 W5 B1 P; y% |7 R
  74.         return $result->getInsertedCount();
    2 F$ y1 d/ o% _9 @& m# G9 k
  75.     }
    9 h; z9 V. G. E' [; G

  76. 7 ]2 x/ N2 E$ |7 m
  77.     public function delete($where = [], $limit = 1) {
    8 f" I: e' v' e+ k7 N
  78.         $this->bulk->delete($where, ['limit' => $limit]);3 X- x" i- B' I- O- W) O) j! x
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);5 r0 L& y$ @/ G+ V' V9 v

  80. * L  j1 m  H0 |; |& \3 z
  81.         return $result->getDeletedCount();
    5 A$ z: P' Y! W1 g/ g
  82.     }3 w; X* \' v& l
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • # p/ g, ?3 x0 A" k# E
  1. new MongoClient();
复制代码

  • 9 k8 G) s3 U2 s0 Z. A
  1. new MongoDB\Client();
复制代码
2.新增

  • , _# Y; t+ i) `  T3 [- T2 A! P
  1. $collention->insert($array, $options);
复制代码
  • ! R8 {3 g, D8 [$ ^
  1. $resultOne = $collention->insertOne($array, $options);//单
    5 {; t# Q* i7 N( B! W+ ^+ x
  2. $lastId = $resultOne->getInsertedId();
    + ~* N1 ]' E2 c' p
  3. $resultMany = $collention->insertMany($array, $options);//多
    3 a; W/ Z# m. i9 S
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • # V4 W' \7 \  d7 @7 _3 x6 _
  1. $collention->update($condition, [; k- b- @9 V" q8 F* k! K4 u7 d
  2.     '$set' => $values
    5 d- S! i4 f+ A! g8 `5 f
  3. ,[
    / i' |# T( X' s& q9 F! |
  4.     'multiple' => true//多条,单条false
    ; V+ g' o$ h0 p! R0 B- _2 x
  5. ]);
复制代码

  • ! N2 a; U8 ~+ s4 R- P7 s& c
  1. $collection->updateOne(* N3 W) ^. U( k  u2 {2 I: |
  2.     ['state' => 'ny'],. Y2 z- u  T* C. ^$ A& m. t
  3.     ['$set' => ['country' => 'us']]) X3 X) G& _" y0 E- n3 S
  4. );
    * H( X% w+ [% p) u
  5. $updateResult = $collection->updateMany(
    * ^8 n$ D9 e* U
  6.     ['state' => 'ny'],' V2 A. H& f- z( l
  7.     ['$set' => ['country' => 'us']]
    ! x  Y) o& X4 u* Q# R
  8. );; W" T% h) A( J, ^6 r8 l3 |: A8 v
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 9 J8 M1 ~" p2 z. ]9 }4 a5 N
  1. $cursor = $collection->find($condition, [
    , `# C  C- N% u' \! Y8 `
  2.     'name' => true//指定字段
    : q; g9 n. s" A5 ~
  3. ]);
    4 D* n+ ^- i6 K" R
  4. $cursor->skip(5);
    3 H2 e% Z9 e$ f1 M) {; u! U
  5. $cursor->limit(5);2 P, U3 o7 D8 h0 m7 ~9 t/ m
  6. $cursor->sort([
    . U7 a5 [# t& L+ c6 F& D: `
  7.     'time' => -14 u( V- Q7 [+ A! ~8 G* S3 y
  8. ]);
复制代码
  • 0 f% Y$ A( {2 x$ {! _
  1. $cursor = $collection->find($condition, [
    ! b+ C3 m# s; |, D
  2.     'skip' => 5,
      s  J! \; ]/ C7 i% A; `
  3.     'limit' => 5,
    7 }( w# s  w4 t4 U/ }
  4.     'sort' => [, e2 Z, _- \7 Y7 U  o& D
  5.         'time' => -1# }4 b5 V! F' `& s0 l- J4 R: A
  6.     ],//排序& g, Z1 a, {! g' o
  7.     'projection' => [6 k. Z; ~1 [: M
  8.         'name' => 1//指定字段
    , [- A8 [+ W1 J3 E1 b
  9.     ]5 P$ B" T% u" ?- Z4 ~7 W
  10. ]);
复制代码
5.删除

  • $ v: @* H8 M7 r1 r; ^- p3 @# G+ Z: I
  1. $collention->remove($condition, [
    " T% A8 m; i1 s/ ^
  2.     'justOne' => false//删单条+ X4 U9 ]# Q! w9 ~* y/ G
  3. ]);
    ! p  r3 F: E) n, E6 B
  4. $collention->remove([]);//删所有
复制代码
  • 8 B# C7 |* y, d
  1. $result = $collention->deleteOne($condition, $options);& b; L* y+ G6 D) K8 D$ E' [: [# I% p
  2. $collention->deleteMany($condition, $options);9 {. i8 S, r% P5 l

  3. ' [0 T+ |+ A( O! O) U. M' L# B( `$ j  m
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([) }& S, e' l* r4 ~, I! v
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    2 T0 N0 Y0 ?# V3 {$ I9 h
  3. ], [$ I2 f8 |- l$ b& Q! D+ @7 a0 g
  4.     '$inc' => ['id' => 1]//自增
    : N. w9 F. e) j. C1 A$ J. J% h
  5. ], [
    9 o) k1 E4 L7 Z3 M' B8 i
  6.     '_id' => 0
    2 F0 F( A( }9 d
  7. ], [
    . r% e& y9 j, [3 d7 u
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    6 d, }0 p7 v: \) t  A) O3 T7 ^/ w( x. C
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([8 R+ X# S2 O/ ~& N0 k
  2.     '_id' => $tableName
    & U9 D. P: t5 @% }
  3. ], [" ^! ]/ V1 B& }6 b
  4.     '$inc' => ['id' => 1]. q  F: U. w7 \/ J4 Y
  5. ], [
    / y2 P& H. u" Y2 v( H  j) ]
  6.     'projection' => ['id' => 1],' }* Z+ u. k( D, V
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    + r) _  D& `- A
  8. ]);
复制代码
; U$ C$ d6 {8 l  Q* o3 F- G

- U% h# U1 m% {! q4 B9 U
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-1-30 14:28 , Processed in 0.071840 second(s), 20 queries .

Copyright © 2001-2026 Powered by cncml! X3.2. Theme By cncml!