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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16542|回复: 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' ]  K1 F3 M! K$ `! t3 ?

  2. . w; m3 h9 N$ M4 S" N7 J
  3. use MongoDB\Driver\Manager;6 s/ X* J' f! y
  4. use MongoDB\Driver\BulkWrite;' v+ x: a" T1 z. J# M$ i5 Q
  5. use MongoDB\Driver\WriteConcern;$ o: a/ T9 E: [* y# Q& g4 {
  6. use MongoDB\Driver\Query;7 D$ S5 `' G( d% @
  7. use MongoDB\Driver\Command;
    1 n# F$ G* T. \8 r
  8. 0 `9 j) {5 W: [. S* f# D! i
  9. class MongoDb {* I6 }* ~8 I$ r
  10. % D  |7 Z" X4 n5 m2 Z0 D
  11.     protected $mongodb;1 F9 C, K. T) h9 B: O! R* Q' {
  12.     protected $database;6 {- v2 F# u+ G
  13.     protected $collection;
    5 A/ g7 D$ i( P
  14.     protected $bulk;' X4 x. {) g5 A. T9 p$ d
  15.     protected $writeConcern;
    : e# |3 n; X8 l3 y3 f
  16.     protected $defaultConfig
    9 X: ~; _8 p8 i/ M
  17.         = [
    & b9 r& I/ F1 S& S/ [) Y2 {
  18.             'hostname' => 'localhost',
    # x, T$ K0 G. ~1 n& s
  19.             'port' => '27017',
    , w+ {; r" c4 {/ m9 u% p
  20.             'username' => '',* U4 a& }( Y* [  ~5 P7 F
  21.             'password' => '',) q0 E% k& @. R2 Z4 E0 y: h
  22.             'database' => 'test'8 o$ X& w6 b7 s6 Z7 m* T  @
  23.         ];
    ) s3 |$ [6 J# ]6 z

  24. , P$ g  m3 H+ D1 T2 b
  25.     public function __construct($config) {
    ; p& e0 T& D: n2 b7 r
  26.         $config = array_merge($this->defaultConfig, $config);
    - Q# Z1 _' ]9 |0 u
  27.         $mongoServer = "mongodb://";; |* [$ U! C. `9 \& y
  28.         if ($config['username']) {- O- y# l* `: y
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';0 _) Q+ z; J. S( [( ^
  30.         }: z: ?8 t' ^- o
  31.         $mongoServer .= $config['hostname'];
      Q! G% N; ~; j4 ^1 T3 b/ F
  32.         if ($config['port']) {
    ; |# Y. E* `* D' ~: V4 K' G
  33.             $mongoServer .= ':' . $config['port'];, ]' {0 g  n  {( Y8 @
  34.         }
    * }0 k- X& ], H% h: ]( Q0 E( h
  35.         $mongoServer .= '/' . $config['database'];
    . v: F7 i' _7 F
  36. 6 I! s8 v2 E6 X
  37.         $this->mongodb = new Manager($mongoServer);& _+ s7 ^; H0 k5 r' _3 w
  38.         $this->database = $config['database'];
    + A1 H: }  v1 s) o7 V2 f3 J
  39.         $this->collection = $config['collection'];
    7 i' x9 G2 O/ j$ L) ~5 D
  40.         $this->bulk = new BulkWrite();
    . `/ L) y" m3 e% m6 C- P0 A& g
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
      i" n3 Q! e( `( O( k
  42.     }
    2 i. G9 P' k5 J3 K! X% e- k5 W0 ~6 b9 P
  43. . g0 |  o" q5 x$ A- D/ C1 D, ~
  44.     public function query($where = [], $option = []) {8 r# g1 {) O* R$ l0 O: N- S, @7 M
  45.         $query = new Query($where, $option);0 }( x* p5 {5 q" o3 ]" P
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);. D2 ]7 D9 T4 n- Q
  47. # C, Q- I  B3 T8 m, d
  48.         return json_encode($result);6 n& L. H, E# ]# S7 S
  49.     }* B) G9 T# f' ?6 y7 h

  50. ) p3 O, D% V0 R! R8 Q. C1 Z/ c
  51.     public function count($where = []) {9 \+ C5 a5 a% r+ [! o) \$ [
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);8 f. |; g  ^* V$ ]$ T
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    ; W8 Y% r7 K( m; z% i2 N) w
  54.         $res = $result->toArray();
    " A4 {4 G5 e9 m) H; c0 ]
  55.         $count = 0;2 s3 W" b: z0 K. r8 O! c
  56.         if ($res) {
    ) c) G9 S: B7 B3 n& V" ~+ l- x
  57.             $count = $res[0]->n;
    & e6 y1 ^& J- ^" n9 h
  58.         }" b7 f* p  G2 b  J4 L5 {( ]

  59. , d0 c1 H" B7 @2 G
  60.         return $count;
    $ I2 N6 h# ^: T) z3 Q
  61.     }8 ]" d' u, N) P0 z) D9 r

  62. # @  L2 [7 t; o  g6 O' W
  63.     public function update($where = [], $update = [], $upsert = false) {
    / V" t# ^$ e6 g1 o" J- W) I
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);# P/ {* [, f+ \6 s
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    : t1 J% n! Q) F! r# `5 \

  66. ' w' R( [% F" ]. J8 Z1 [
  67.         return $result->getModifiedCount();% \0 R7 F' F7 [
  68.     }
    - W+ j; u% S+ ^: p$ W& v; k

  69. ! W6 ~3 A) @1 g$ m, n
  70.     public function insert($data = []) {. j1 ~. ]/ c: {" X  u1 R/ y& N
  71.         $this->bulk->insert($data);$ s+ [6 B3 G0 x9 _! W; t0 @
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    2 @1 Y7 j$ D& U  s; y% K# p/ s
  73. & Z; U1 x$ y+ ?" l& q+ e- {
  74.         return $result->getInsertedCount();
    - }! e9 L  K" |. i. J: S
  75.     }
    2 B3 \6 ~" G# x" J8 Q( O

  76. 9 J9 s& @2 e! ]3 B
  77.     public function delete($where = [], $limit = 1) {1 i7 L2 J* q, Y
  78.         $this->bulk->delete($where, ['limit' => $limit]);* C% m  `8 ?% a: G2 b3 J' S7 n
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);: y& `7 T7 Z" P4 e( V2 p
  80. ; B# I4 ^/ z! j6 g
  81.         return $result->getDeletedCount();
    # L! y5 @' }1 G! J) ]6 g
  82.     }
    ' v1 n& D' a2 S: c) t) B3 ^/ f
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • , h; u' \/ {. ~' e+ m
  1. new MongoClient();
复制代码
  • 2 `7 _& ~0 o( J/ M' k* Y* s
  1. new MongoDB\Client();
复制代码
2.新增

  • 5 T1 D" d. w- s, i) z" G0 m% }
  1. $collention->insert($array, $options);
复制代码

  • % [, M* ^2 B1 t
  1. $resultOne = $collention->insertOne($array, $options);//单
    % f8 E( t/ c- X) I% z
  2. $lastId = $resultOne->getInsertedId();3 L' r% g. ?% L: y9 @7 L9 C
  3. $resultMany = $collention->insertMany($array, $options);//多
    / P  P; B; n& W- c  j, z: V
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • , _  w' N/ h- l7 x- z% R6 Q" @" ]
  1. $collention->update($condition, [) o5 \7 G! F0 ^% P
  2.     '$set' => $values( S; J* ~& Q6 [4 i
  3. ,[! G9 v) T. v! E4 O$ {
  4.     'multiple' => true//多条,单条false
    9 {4 x, J& v5 j9 A7 d, N9 v
  5. ]);
复制代码

  • # ]* p) F' n% n6 k
  1. $collection->updateOne(' z% G( ^3 _; g: ?6 ^/ g
  2.     ['state' => 'ny'],5 q) ?( i4 t+ O; v
  3.     ['$set' => ['country' => 'us']]
      Z. U+ c& O' g9 I: m/ ?" {  d: o
  4. );
    / c4 T! Z& a  H: c# I
  5. $updateResult = $collection->updateMany(
    ( M' P: e. ]& M5 s
  6.     ['state' => 'ny'],: t9 n- L+ c( {( c2 k
  7.     ['$set' => ['country' => 'us']]& Y; P5 n8 L0 d; u1 ]' o/ o
  8. );8 Q, x1 ]/ ]+ w7 Z
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • + ?; \4 }  l, r( B) k
  1. $cursor = $collection->find($condition, [' ?+ o; k) K% u+ v+ c2 L
  2.     'name' => true//指定字段
    6 R- {6 i  b* x! @# O
  3. ]);
    3 @, h3 e$ L6 k: H
  4. $cursor->skip(5);
    ! c9 `; d$ {# m) k# `1 G# ^: A
  5. $cursor->limit(5);0 Q: f# a2 [2 i. O, d- @
  6. $cursor->sort([0 m! z; o1 f4 B3 R8 `# J3 M- j, s
  7.     'time' => -1" ]- d: Z0 S/ j9 a3 s( J
  8. ]);
复制代码

  • ; Y5 Q  L! L* b7 S  z# ^: D
  1. $cursor = $collection->find($condition, [
    & d% s# m2 d+ j* B( g" H
  2.     'skip' => 5,
    ( a$ {0 F6 F5 t0 d
  3.     'limit' => 5,
    8 O3 Y6 C7 A+ M; \3 F" o+ ~; K
  4.     'sort' => [
    6 p7 O: }& n% u8 w; z7 j7 X
  5.         'time' => -1
    ) P! o: a' ]4 v# O7 M
  6.     ],//排序
    ( r8 y; S8 P  J1 r" t2 \- K
  7.     'projection' => [
    $ k. e+ P, ]6 C7 R/ t) X
  8.         'name' => 1//指定字段/ h, ?% i7 b7 V2 F$ m
  9.     ]
    , d# ?4 z- m; X) J& Y4 ?0 q$ M; {, H
  10. ]);
复制代码
5.删除

  • $ O! J# k* S. W- |0 S5 E( B9 n
  1. $collention->remove($condition, [
    ! u' M1 V) q1 D" ]8 `) q
  2.     'justOne' => false//删单条2 [+ ?% w3 A, [# o- q% A$ J: [/ [/ l
  3. ]);6 P8 j  z2 J. D- L
  4. $collention->remove([]);//删所有
复制代码

  • 0 H8 m. W( d. G
  1. $result = $collention->deleteOne($condition, $options);
    6 l$ |; d6 T3 ?: @) T
  2. $collention->deleteMany($condition, $options);
    ) A! ]' l6 V" g2 \3 C

  3. $ R3 A& f8 o/ t7 i( j- ^
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([. L3 D" X* `7 G
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键4 o1 z  y, T" h" B( E
  3. ], [% J% s: @# m# ^9 v
  4.     '$inc' => ['id' => 1]//自增
    4 z  [7 ^( u, x5 Y4 u9 H3 R
  5. ], [
    8 W4 X- }- C+ l( y+ R- p. }
  6.     '_id' => 09 k8 U" p  r7 Y7 b, V* W4 k* t: c
  7. ], [
    + A- U4 d2 w. @
  8.     'new' => 1//返回修改后的结果,默认是修改前的) b) x9 K) C! P) n* v; z7 _3 ?5 r
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    , o5 Q2 ?- h" b2 y/ o4 y
  2.     '_id' => $tableName$ s% O. o7 m2 ^; V; l
  3. ], [/ G8 g: r7 r2 \( s+ H, O
  4.     '$inc' => ['id' => 1]
    4 A# d& e  i3 c" R
  5. ], [
    " ?& }! v1 Y; S9 |# Q3 c/ X
  6.     'projection' => ['id' => 1],1 m4 {6 v4 M4 M8 f0 ]( e* C
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER# m/ X# O/ F: T! _) i% e; c1 z  C
  8. ]);
复制代码
& b0 ^& z9 y: Q* ~* Y; R

4 _4 N( c9 l& q  M
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-19 22:44 , Processed in 0.050870 second(s), 19 queries .

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