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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16100|回复: 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$ K& Q- A7 m' }
  2. 8 Q9 d% [$ K4 a3 f) I( l  h
  3. use MongoDB\Driver\Manager;6 q1 f9 t  ~: Q7 z
  4. use MongoDB\Driver\BulkWrite;: j. S' a& G9 d+ J% _
  5. use MongoDB\Driver\WriteConcern;# x) [5 n% ?0 p4 I, x: x. R
  6. use MongoDB\Driver\Query;- n2 u( o3 e0 Z2 \3 Q
  7. use MongoDB\Driver\Command;* L2 |8 l, \. a. J. ]- y: y
  8. . {: M) u9 p. E1 i/ g
  9. class MongoDb {' s# E4 i& f' J/ d; k

  10. ( X( w2 b+ h2 ~6 d
  11.     protected $mongodb;' @, L( H& e3 T" ~& z! I
  12.     protected $database;" F, W- e/ G8 T. H7 J8 N
  13.     protected $collection;* X; e2 F+ Q; V+ q' H$ {  o
  14.     protected $bulk;/ M1 I) |4 o9 G3 y* B
  15.     protected $writeConcern;
    / [) R$ Z7 S  @' A2 V
  16.     protected $defaultConfig/ |+ S, y9 `& L" [' G8 b. z8 A
  17.         = [
    + O7 F6 W& i! }" i% {2 N
  18.             'hostname' => 'localhost',
    0 c6 m% m" J5 j1 G# H
  19.             'port' => '27017',
    : D2 F- h+ p; w6 C5 `
  20.             'username' => '',
    - [/ d- D! q& K4 ]6 @9 |/ M
  21.             'password' => '',
    # k" z' n* P7 C: `
  22.             'database' => 'test'
    + q% q2 k5 ]. m2 [
  23.         ];
    - t2 `# c  D+ Q" S
  24. * I$ H7 e) S) b% q/ a" I, _1 R
  25.     public function __construct($config) {% U0 P& s3 T- T
  26.         $config = array_merge($this->defaultConfig, $config);
    7 E9 m5 y4 o$ F/ z5 {
  27.         $mongoServer = "mongodb://";" g. X3 B7 b  I$ m
  28.         if ($config['username']) {
    ; o& G- V* P, V7 J& ?4 s
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';5 K' B1 `' N  y3 o; K% E
  30.         }6 q4 m. Q" @/ w; O$ J/ a( @% v6 A* L
  31.         $mongoServer .= $config['hostname'];& l: p( d( L: B
  32.         if ($config['port']) {5 a2 p+ u- m6 `8 F% `5 l
  33.             $mongoServer .= ':' . $config['port'];! f, O, q7 ]6 [/ ?
  34.         }3 f6 G3 k4 q4 u! g7 j! z5 [. Y
  35.         $mongoServer .= '/' . $config['database'];' S6 _) x+ C" k! t+ V

  36. " ~$ o5 U! M! k. o+ g
  37.         $this->mongodb = new Manager($mongoServer);
    2 @2 P+ G0 k, [: k/ y# s
  38.         $this->database = $config['database'];/ D+ h2 y( O, n: }' c+ }( k
  39.         $this->collection = $config['collection'];
    8 \, @: D+ A( w" C  [3 t' g- Z
  40.         $this->bulk = new BulkWrite();
    " b& W( m/ m( J
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);- v2 K6 _, W- E" z
  42.     }+ E0 i+ z: h' O1 o

  43. 6 B. D" Z' a2 |1 U# g" j
  44.     public function query($where = [], $option = []) {
    4 ^" p9 Y- h2 s" Z0 _1 U
  45.         $query = new Query($where, $option);
    4 p; T8 Y* b: Z2 H$ y$ x
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);( i, y* Q8 V3 Q

  47. 7 d) s8 b; Y8 N9 z- L# x, Z# U
  48.         return json_encode($result);. _) z6 S; h! S3 U
  49.     }" N% c$ c/ g+ T. D0 w

  50. / |! L  `% \9 y( G' E9 B1 s( Y
  51.     public function count($where = []) {
    ) G6 w8 ]2 A- b% u2 |, j  l$ `
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);1 _$ o& x  H" R$ P$ U4 |
  53.         $result = $this->mongodb->executeCommand($this->database, $command);8 \: C2 r! T5 L" q( L9 i1 `! W
  54.         $res = $result->toArray();
    + E% A! ]; r) W6 c4 o  D6 Y7 i
  55.         $count = 0;
    # Q3 t" l* W" c' {7 \$ J1 R
  56.         if ($res) {9 `; F1 F1 {+ @' u* E
  57.             $count = $res[0]->n;; E5 _9 F% [7 j; g- M5 ]5 m0 m6 ^
  58.         }6 \$ Z7 S7 C0 d
  59. 2 X0 b6 W6 g/ i
  60.         return $count;
    7 r+ |5 k5 c' r+ \2 ?, y$ x
  61.     }) G3 c# }+ u: @1 c& V/ L

  62. ; A  B( x* [' O
  63.     public function update($where = [], $update = [], $upsert = false) {
    ) b$ o# Y; Z8 d9 M5 h
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    , k7 n  x% _" g1 H
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);' [9 |" w& X6 E: e4 @0 D
  66. ) c) b- W; }0 |. T
  67.         return $result->getModifiedCount();- A1 B! p8 u8 h3 N+ [8 a. \! t9 I
  68.     }
    : d, ^8 W4 K. u7 H* B5 s
  69. & d3 B+ @# a# w( U
  70.     public function insert($data = []) {
    5 l. W  l3 F9 o: e( n: N7 p7 p$ M: u
  71.         $this->bulk->insert($data);# o/ ?& D/ z& `, e; M
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    - h2 c+ F1 v5 n3 L+ i

  73. 0 [; h( R5 N: }: u0 O$ U& M
  74.         return $result->getInsertedCount();; ^6 A1 z) N! n, u7 N! g  ^, S
  75.     }7 d* L5 Y, ?) |% \8 Y. m
  76. ) y) C/ I$ E' a# X
  77.     public function delete($where = [], $limit = 1) {
    # U  |: D7 m% o9 {
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    + D$ k4 K% `* R' H) Y
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);! x  L( M, a* u% M8 z; X6 _/ e

  80. 9 k7 g; Y: y( b1 s
  81.         return $result->getDeletedCount();
    3 @  ~- J, t& t9 Q$ ?6 H
  82.     }! T4 h* V& H" I
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • . ?- f! I1 R% J
  1. new MongoClient();
复制代码
  • # }. C$ B& n. |; p: c
  1. new MongoDB\Client();
复制代码
2.新增

  • ! f3 z5 y  A7 O( a- {$ O
  1. $collention->insert($array, $options);
复制代码
  • 1 k* J( O, l: f$ @
  1. $resultOne = $collention->insertOne($array, $options);//单
    9 {2 b; [1 |  [8 k+ ]
  2. $lastId = $resultOne->getInsertedId();
    2 M) W* H) @* q5 _9 ^
  3. $resultMany = $collention->insertMany($array, $options);//多( e7 v0 t6 C8 A5 Y6 |! z
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • , U& ]: ]2 L0 P0 t, b, T! M: W/ Q- s
  1. $collention->update($condition, [8 c) x. w) W9 f6 h
  2.     '$set' => $values
    * ]# ^6 |' P( |, \0 Q- [
  3. ,[& M" O. x3 |9 Q# h
  4.     'multiple' => true//多条,单条false6 x+ d" H; p6 e+ O) b" l. e; ~( o
  5. ]);
复制代码
  • & Z$ c+ u- M4 \+ n! `2 T1 L
  1. $collection->updateOne(# l0 Y# B  E$ T! D7 B% B
  2.     ['state' => 'ny'],
    6 Y/ M: O0 Y( Q! A% U! {
  3.     ['$set' => ['country' => 'us']]( e' O6 x( b- Q# U% f" R1 l$ K
  4. );
    . a  ?& ]* b: Y: B% R5 n9 O
  5. $updateResult = $collection->updateMany(  t( f: M1 f  j) A. _% `
  6.     ['state' => 'ny']," n# o+ w$ I. {) e* t3 H
  7.     ['$set' => ['country' => 'us']]
    8 A) t$ ~9 ~, x" `! k; c0 H
  8. );8 X: p. w4 @: p
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询
  • 8 Z8 z4 y. m& N0 |+ m
  1. $cursor = $collection->find($condition, [" \& B+ a7 p% s. D- j7 N& M
  2.     'name' => true//指定字段3 T- J7 y& H! r/ \3 W1 L" m
  3. ]);
    + v0 d5 K/ W% k  ~
  4. $cursor->skip(5);
    0 L2 v$ u+ g) h4 O8 R+ h3 ^9 x
  5. $cursor->limit(5);
    & U; u: g* T9 Z; J
  6. $cursor->sort([5 r5 a. e. [, n4 Y6 l
  7.     'time' => -1
    $ I+ W( X) V+ V+ _  e* C
  8. ]);
复制代码
  • & a4 L8 Y8 R! \
  1. $cursor = $collection->find($condition, [$ b: D' V4 Q5 k0 z$ v* a
  2.     'skip' => 5,
    8 J' `) Q2 L, v. J
  3.     'limit' => 5," X) W! M/ X8 L: w
  4.     'sort' => [
    + |+ n# P# Y2 |' ~: D
  5.         'time' => -1
    ; X* p1 b4 X4 Y& Y: a7 f$ f9 U+ L2 I2 ]
  6.     ],//排序  M1 C& O, E/ X3 D
  7.     'projection' => [+ u# V" u- p- \  F
  8.         'name' => 1//指定字段; i, W$ a, _8 G1 g. u+ M: D
  9.     ]1 R. \7 G0 t2 _- W' B* K. D- Q
  10. ]);
复制代码
5.删除
  • / D4 f4 i: D/ r/ g: ?
  1. $collention->remove($condition, [+ i  @+ }/ U. Z" W  m  P
  2.     'justOne' => false//删单条
    . W5 N% m( N$ R% h
  3. ]);: A! C+ C  i* R: r: g% d: d
  4. $collention->remove([]);//删所有
复制代码

  • : D& t- a" R/ t: f  _6 M
  1. $result = $collention->deleteOne($condition, $options);
    2 O# y$ L% l& C
  2. $collention->deleteMany($condition, $options);
    % v/ i3 v9 ?$ ?! }) k9 Q+ E3 |3 d
  3. * w0 F8 Y0 Q' [- R, W
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([( C, M, ?0 T9 |4 v
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键! D! e0 h, a5 [8 s9 @. O2 ?  F
  3. ], [
    : T3 x- d* h9 `$ m
  4.     '$inc' => ['id' => 1]//自增# x- z# a/ _7 @: n3 R" i
  5. ], [
    5 ]( c3 f* Z: h& ]! ?1 e
  6.     '_id' => 00 o; c* q: h+ d1 S
  7. ], [
    ; r5 L. j, x9 \' Q8 K
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    , u4 h4 O) L/ E
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([5 ~! M6 Q! N* @% s
  2.     '_id' => $tableName
    $ C) L. s/ G1 S5 w
  3. ], [, }: X. f# s3 g& S8 t+ c, x
  4.     '$inc' => ['id' => 1]" c' I% N" E  D" k
  5. ], [3 U- h- d# B4 y! F/ X
  6.     'projection' => ['id' => 1],1 ~8 w0 X+ d7 X0 ]
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER7 X1 k7 s, l- j9 o
  8. ]);
复制代码

/ w9 ]6 B1 m$ v* v% v* D
# C5 q7 |" m, ?7 V
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-3-17 20:17 , Processed in 0.065047 second(s), 22 queries .

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