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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11192|回复: 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
    8 ]. q' `$ k$ @4 ]8 }8 z$ i+ D

  2.   U7 O6 I+ c: t; o! v& d
  3. use MongoDB\Driver\Manager;4 w, Y* o# I( e( O% O
  4. use MongoDB\Driver\BulkWrite;
    3 M1 d8 e+ [) M; ^& K
  5. use MongoDB\Driver\WriteConcern;
    + B* T- n$ E$ J: s: Z
  6. use MongoDB\Driver\Query;
    3 P7 ^! P  d( a+ M2 Z* h* S
  7. use MongoDB\Driver\Command;- w2 v7 N4 C! e2 ^/ V$ f' B0 l

  8. 0 M- u& X" {; T, T
  9. class MongoDb {3 Z& m1 ~8 R' |3 y

  10. ' L4 \  Z: ?: I, C3 t
  11.     protected $mongodb;! `* o9 Q/ }8 X
  12.     protected $database;! {+ c% O( D8 v; ]2 W( h
  13.     protected $collection;2 Q) I8 k4 K: X
  14.     protected $bulk;
    , d8 k" l$ u$ v. |- n' [
  15.     protected $writeConcern;8 j7 U; p& q! W6 h
  16.     protected $defaultConfig
    0 l, B; `6 b4 A+ C% G/ f/ @
  17.         = [$ ]7 {5 A# @  y+ e$ x4 @  m
  18.             'hostname' => 'localhost',5 {) |! S* u0 y0 e5 }. k
  19.             'port' => '27017',; Z- B6 I. q9 W) J  f$ J+ g2 N
  20.             'username' => '',) F( L$ K( A* O, e
  21.             'password' => '',/ S! j1 ?8 i4 h/ L. t$ X! H# E% G3 {
  22.             'database' => 'test'
    - X6 J; Y% z% U) s7 r
  23.         ];
    ; q3 n/ c% U0 V  V* b% ^5 z

  24. 8 g" k0 U# N! o( t( [7 z
  25.     public function __construct($config) {  Z4 [2 J0 D" j
  26.         $config = array_merge($this->defaultConfig, $config);
    % ~' U, E2 p+ x, r
  27.         $mongoServer = "mongodb://";' ^: E( X5 w5 F% T
  28.         if ($config['username']) {) [9 S, z5 |3 m. m( A, v" X
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    $ l7 Z! h# f: f; Q
  30.         }
    - \1 A+ i6 _# ^% N" X9 r- b
  31.         $mongoServer .= $config['hostname'];4 m  |' I- J: ~! s. F
  32.         if ($config['port']) {' C5 j; n8 K& y5 E4 J6 O8 N" U
  33.             $mongoServer .= ':' . $config['port'];
    ( I3 @) m& O/ k2 z8 i" a# o
  34.         }% H, A  r. B5 G: e" a: s: A
  35.         $mongoServer .= '/' . $config['database'];
    - M8 n; y3 V% g5 r" F* H' t. y

  36. # t3 ?2 _" R' m  t9 J3 M" O
  37.         $this->mongodb = new Manager($mongoServer);
    2 m( B8 I  R3 q8 {, n
  38.         $this->database = $config['database'];
      v0 ?' S0 H- j3 }
  39.         $this->collection = $config['collection'];  w, Z) _( f& `* i: q0 j9 W
  40.         $this->bulk = new BulkWrite();5 E  J5 C! a4 I
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    - K, r3 D# S- E# T
  42.     }  a3 B- }- N  B# ?
  43. - O# D2 f* }4 P
  44.     public function query($where = [], $option = []) {; o7 L/ s; l$ m5 J: h6 Z
  45.         $query = new Query($where, $option);  G0 ^* Y0 k, W- @
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);1 E+ d# V: D$ {9 X6 ~6 B% Y$ `
  47. & h, `' D. }7 T) v& m6 V
  48.         return json_encode($result);) o  j" y' I& U# R% a; Q
  49.     }
    2 ]% N" m) O  R7 a- O
  50. . Y7 d$ m* C& H1 z7 A
  51.     public function count($where = []) {/ K7 M. s8 q% A' T
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    1 Y  K$ z" z3 W1 w- g5 n
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    2 w& d# M; t/ _1 X
  54.         $res = $result->toArray();
    . y  H+ R9 u  K7 D# w9 Y
  55.         $count = 0;$ Z5 C. o+ J. K% r5 O; D
  56.         if ($res) {3 s  a# q5 I. \/ X3 S2 d1 W. t0 ~  \
  57.             $count = $res[0]->n;
    0 x, ]9 ^3 j! ?+ f
  58.         }
    . S3 O# J1 P( S* n/ o

  59. ) w4 Q) s' {2 i6 _9 ?; @1 L
  60.         return $count;3 i3 E: `) p9 [% L
  61.     }
    " R6 y9 Z- e. E$ c- E3 g8 \5 X1 r; k
  62. % H+ [& N  U3 t- A3 k' a2 A
  63.     public function update($where = [], $update = [], $upsert = false) {! h9 n- j) x4 a: r) s  U7 c0 s
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    ' M: B; a. @, L# ?& Z
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ' E  P4 M$ T. s0 A  a1 Y; I+ L
  66. : p& |- h  ]. [9 H( e2 y/ ~9 s
  67.         return $result->getModifiedCount();
    # S7 Q" W" \) d% j1 a
  68.     }
    & L( s( E) f5 U) [" s6 B7 `0 s
  69. 7 I8 y+ A) W- A6 Q  j7 n; P
  70.     public function insert($data = []) {
    : p" W  w5 O. T4 ^9 V) _  U, m
  71.         $this->bulk->insert($data);
    * E6 ?5 \5 E- x2 r" k; F4 |
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    . E8 j* w* c7 E( ~: e
  73. % ^8 F) \; H5 r: p/ B/ b; o
  74.         return $result->getInsertedCount();% ^. {/ o4 q* g# C, @+ ~3 z
  75.     }5 o9 `9 ~/ S8 V; g2 i1 Q/ o
  76. 6 U; T; P: N. n7 G7 `6 X
  77.     public function delete($where = [], $limit = 1) {! H1 A$ s3 o. y
  78.         $this->bulk->delete($where, ['limit' => $limit]);. L" O$ b. O1 b, Z* |7 G: _( o, y
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);1 k8 ^. E) X, K1 t2 F% U% c* \- ]
  80. ; b* l' V, ]4 V4 f. X
  81.         return $result->getDeletedCount();
    2 @* `6 ?5 S3 x1 ?
  82.     }' J  s* F  t3 f& P. ?9 ?! r
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • + P6 _# q  l: J
  1. new MongoClient();
复制代码

  • & J6 q, f3 A1 O+ L) D
  1. new MongoDB\Client();
复制代码
2.新增

  • ( f! o) J! _# M/ ]+ w) ?& B- F- E
  1. $collention->insert($array, $options);
复制代码

  • $ d# l6 Y# l$ ?0 k! V
  1. $resultOne = $collention->insertOne($array, $options);//单7 m. K# |" r9 g2 J; y8 t9 `
  2. $lastId = $resultOne->getInsertedId();
    # T. ]' ~% p6 R! r) u0 o* ~
  3. $resultMany = $collention->insertMany($array, $options);//多' B6 t9 Q3 C# q  g5 I
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • ( _9 i2 i2 y" }% y% \. H
  1. $collention->update($condition, [
    ; J: x) c4 Y3 G6 p$ F
  2.     '$set' => $values
    + F" G4 Z1 Y5 ~6 s7 R
  3. ,[8 _; b* T) ~5 e9 D4 F! B4 A6 _
  4.     'multiple' => true//多条,单条false
    ) m' I$ J/ n8 H" Q! H% S
  5. ]);
复制代码

  • 0 l' ?8 q' K& @: S4 y9 W$ H
  1. $collection->updateOne(' u* l* G& o! l4 N
  2.     ['state' => 'ny'],
    " ]% K  v- \: |( {' Z
  3.     ['$set' => ['country' => 'us']]# n. }& r! c& P
  4. );2 Z+ f" ]- D5 W+ T( y6 T
  5. $updateResult = $collection->updateMany(
    9 q, o" H2 x# v* m* l2 P2 [
  6.     ['state' => 'ny'],
    ; r8 ]" D' ]2 o/ N  ]
  7.     ['$set' => ['country' => 'us']]) m: v4 ^* ^( Z0 E
  8. );
    6 U8 n4 z0 `5 j& x% e/ y
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 9 k! S# F; `) A2 K) X4 p
  1. $cursor = $collection->find($condition, [
    6 v# u1 p# i1 ?4 S- Q& R
  2.     'name' => true//指定字段7 s1 h  k$ V$ k8 v4 T- z4 \9 G  I
  3. ]);
    6 W9 G/ h' P) h% }
  4. $cursor->skip(5);& ]; E4 e& Z1 S8 M
  5. $cursor->limit(5);+ ~. R# Y  Z6 b; m$ Q7 G
  6. $cursor->sort([1 Y$ @# H" E0 z+ [: X
  7.     'time' => -1
    , y2 l# j7 i. ]# @( O5 Z5 ]
  8. ]);
复制代码
  • 6 Q$ S) q& n- o0 ]
  1. $cursor = $collection->find($condition, [
    $ W- e; y  t0 ?5 Z3 B
  2.     'skip' => 5,
    : Z. o6 g: c+ r+ h% Z; E& [3 ~6 |
  3.     'limit' => 5,* `% ?" b; [# ~. x  a; i4 D
  4.     'sort' => [
    % [2 j: w3 b6 ]$ f  Q* F2 e2 U' D" {0 }6 S
  5.         'time' => -1% W4 x, H2 @$ k2 [
  6.     ],//排序/ p8 J2 b% T' L- y
  7.     'projection' => [
    ! n/ ?" K/ R5 A8 Y$ F2 T, r/ q
  8.         'name' => 1//指定字段
    & ^$ m5 S% _2 K+ B& i2 E
  9.     ]& b7 ^8 x5 _/ V" x6 L  Z& c/ R
  10. ]);
复制代码
5.删除

  • . {( i0 `& w# @+ Z) `) D1 @+ F
  1. $collention->remove($condition, [, A; T! F0 Q  I1 i5 ^4 W
  2.     'justOne' => false//删单条' I; s) _# w* Q! x) d3 T5 ?6 r; z* L
  3. ]);+ Q6 b5 Q8 ^, u5 R/ `6 x  |
  4. $collention->remove([]);//删所有
复制代码
  • ' f5 i: @1 ^, o' c
  1. $result = $collention->deleteOne($condition, $options);
    * E. U1 ^% l3 Z, q* V, l. u: k$ C
  2. $collention->deleteMany($condition, $options);
    * ]. n) A1 A  Q: n: W* h
  3. % e$ A/ Q+ Q4 z. o8 |& A6 s: x
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([1 j1 j3 z& T7 d/ P$ W6 |% Q. ?
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键) t" T  w& Z/ ]3 O9 E! b
  3. ], [
      T2 [1 T8 D! |/ p1 x
  4.     '$inc' => ['id' => 1]//自增
    8 S- k- p0 b7 G
  5. ], [9 X0 [7 X% |2 r6 m! h# J. I
  6.     '_id' => 0$ h- B5 F3 L6 Q1 ~) }3 e) W* d
  7. ], [' I) |( u+ J' n& x4 E/ T% e
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    " H* E3 U8 O2 ]; x$ l- D
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    : d* K; ]8 u% a# }$ |. F
  2.     '_id' => $tableName
    ! r  E: B- `* i, ~, P( G1 w" p
  3. ], [& {& _' N& }6 Y' t! }
  4.     '$inc' => ['id' => 1]' j% h1 f8 @6 `: ]* t  n
  5. ], [4 w, g. y# Z$ R- X/ y  T
  6.     'projection' => ['id' => 1],
    $ X& Y* G1 m7 p$ }
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER  c, {/ ~1 d' S2 J! v
  8. ]);
复制代码

4 g6 Y4 A$ Z2 V$ b7 k8 t0 h2 i3 o
) J6 V0 T7 V, J5 H
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-1 21:54 , Processed in 0.110888 second(s), 19 queries .

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