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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 17010|回复: 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
    1 [- J* A" @" M/ |" x/ A5 u

  2. ! B, ~" N0 E- t
  3. use MongoDB\Driver\Manager;$ Q- `; c) M  m' O2 l7 k
  4. use MongoDB\Driver\BulkWrite;0 I9 \! z% S3 I( n
  5. use MongoDB\Driver\WriteConcern;
    7 f, o0 ]/ G( k, H% I# Q/ H
  6. use MongoDB\Driver\Query;1 f. e; m2 G& k
  7. use MongoDB\Driver\Command;3 S, T4 J. c/ }, b( E! ?

  8. / N+ w/ t3 j- C# A( E( o- a
  9. class MongoDb {3 k5 R9 H9 I' Q
  10. 9 B$ W6 i) X. V3 ^; R2 F
  11.     protected $mongodb;4 d" C% I. o. k# @9 z9 P$ q5 X
  12.     protected $database;. v& h/ B9 `% x  b
  13.     protected $collection;  u8 m. d* n# ~- I6 w! b1 _6 j
  14.     protected $bulk;$ W6 j; K1 @9 c$ z8 Z1 C
  15.     protected $writeConcern;
      j4 K# z9 h+ `% \0 E& H0 l
  16.     protected $defaultConfig. Y8 \, x1 }7 U* A4 X
  17.         = [1 s6 ?! M/ B$ p& k. h0 C6 u
  18.             'hostname' => 'localhost',
    * c# z: S8 W  D- H" N- [
  19.             'port' => '27017',
    8 B& y# [0 ~! o
  20.             'username' => '',4 l$ I0 v( c0 x: b+ J9 O. F1 L1 `
  21.             'password' => '',
    ! O3 b* D# J/ p- M: z
  22.             'database' => 'test'1 k% _' }; y. w! W3 g9 M, E- ?/ x
  23.         ];
    $ {6 E+ _, _/ N6 S7 Z' E
  24. : o3 a7 P" t  ?( H
  25.     public function __construct($config) {
    # |  T3 O  V2 X! r  d+ M' R7 H$ H
  26.         $config = array_merge($this->defaultConfig, $config);* Q7 k& g( I; R7 l
  27.         $mongoServer = "mongodb://";% ~) j' B* b5 v* g
  28.         if ($config['username']) {
    9 O0 M1 V8 \; ]. V# K
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';2 j  n$ f4 v; s. Y
  30.         }# F) [! v% ~0 |& f1 J7 G
  31.         $mongoServer .= $config['hostname'];9 [, a7 H* a1 H. A2 Z( T
  32.         if ($config['port']) {6 O% n7 o# @+ ^, A
  33.             $mongoServer .= ':' . $config['port'];' X& c: }1 j$ j" o+ ?9 H3 i' l- D9 ~
  34.         }) m  m- h) L3 u+ @  S
  35.         $mongoServer .= '/' . $config['database'];
    ) W3 r% }2 ?/ n' m
  36. 1 \/ ^! p- ?. r9 r& M; V2 R
  37.         $this->mongodb = new Manager($mongoServer);& w+ S0 k, P6 T$ i
  38.         $this->database = $config['database'];
    8 V' D% I% i4 m0 p- @6 K# U! c. b
  39.         $this->collection = $config['collection'];# e9 J4 E: y5 t
  40.         $this->bulk = new BulkWrite();
    4 f/ Y9 N! J4 p
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);4 @  X& b& e! N  D' k8 G# t) l: g, T
  42.     }: T* v- m5 E& ^; Q

  43. 1 d  j# O2 S1 k
  44.     public function query($where = [], $option = []) {6 V: O/ w/ T5 j5 K5 J" ^2 f: @& r
  45.         $query = new Query($where, $option);
    ; e* @1 g- f9 @. U2 M0 \) r+ R
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    ( T3 Q4 u/ w6 {* ?3 n3 S
  47. / L3 [$ Y$ ?! ^: F& x% Z8 [* |. c& w
  48.         return json_encode($result);
    8 ^7 c. G% G  @% O( f7 ~7 B
  49.     }
    3 C2 T. q) W6 i6 U% ~4 a) f

  50. + G# B, w$ F. M- b* w& r  ?6 D$ }1 x" \
  51.     public function count($where = []) {8 ]- O  f9 t: D: W' E5 @
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    6 N5 m; j5 F- V% ]6 l
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    ! c' l9 Q" a4 o# x1 e+ F- }8 ~
  54.         $res = $result->toArray();
    + D4 i, p6 k- J2 O% p6 [6 R
  55.         $count = 0;
    3 C8 ~( u: ~7 r) C* w4 G
  56.         if ($res) {4 A" d  s2 Q+ H8 ]  u
  57.             $count = $res[0]->n;/ O: j1 e+ H3 `1 H5 n
  58.         }3 k$ \' @2 G: f" q& e
  59. * T7 }+ k: j8 y) h
  60.         return $count;' L/ T: o" ]+ C/ m, e/ Y
  61.     }
    - h6 v" i) V! m% v9 t! U+ H

  62. 0 L' Q0 V& d. X# h  L+ K2 X
  63.     public function update($where = [], $update = [], $upsert = false) {, r. g# ^/ e/ x- ~/ r
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
      h0 j7 V1 I4 s! X, S" s
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);& m( P6 L% H: x$ ]) g2 X! E

  66. 2 _  C3 j+ P1 z4 Y
  67.         return $result->getModifiedCount();& |- B) ?. e: }% q' U
  68.     }* C3 u5 X0 w$ s, U
  69. $ i$ T) o$ m3 @2 s* J  L
  70.     public function insert($data = []) {
      C: m9 m3 M/ W
  71.         $this->bulk->insert($data);2 Z" A% g4 u3 q' G% W
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);6 V! `4 b: C% |) N  n

  73. 2 i& |) {% k1 ]
  74.         return $result->getInsertedCount();
    7 Q; Q+ f1 d: c3 B; c: J- ~
  75.     }
    8 H  v0 v. {  T

  76. % }, j  B2 U1 Q; R4 E
  77.     public function delete($where = [], $limit = 1) {. [3 ]  _9 E9 K& f* v
  78.         $this->bulk->delete($where, ['limit' => $limit]);0 o. [# A5 j7 z1 [
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    % r; w& z$ l; u% ?: ^3 O1 v  }
  80. 8 S3 ^, u. s& h3 {2 _
  81.         return $result->getDeletedCount();3 P, v) o+ m5 ^& e& C
  82.     }
    0 S* v# o2 E7 n8 B
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • - n1 j& E" r# J/ m, n3 u. j. [& k
  1. new MongoClient();
复制代码
  • % y& E6 S9 W) A. B& }
  1. new MongoDB\Client();
复制代码
2.新增
  • - Y. }) N$ P6 p% q! ?% V
  1. $collention->insert($array, $options);
复制代码
  • 5 {5 ^. x7 i( N( |4 H8 p5 _
  1. $resultOne = $collention->insertOne($array, $options);//单# b0 w& X0 a2 |* x, Y( r6 K  L3 g) J
  2. $lastId = $resultOne->getInsertedId();- S: q: f3 p0 z: a
  3. $resultMany = $collention->insertMany($array, $options);//多
    * q. J- {, T, a
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • % [; g: ^+ S. Z& f
  1. $collention->update($condition, [$ z! Z  `4 y. `
  2.     '$set' => $values4 j9 ^5 }% Z+ T4 m2 W
  3. ,[
    ) h4 I9 T2 ~6 Y, Z8 q0 E
  4.     'multiple' => true//多条,单条false
    ( d% h# z" p# O% p1 }- b
  5. ]);
复制代码

  •   V7 f  O4 \! u
  1. $collection->updateOne(
    ) q+ T; f  S& f) Q% \! s; D
  2.     ['state' => 'ny'],. g& [, j* p/ Y" U
  3.     ['$set' => ['country' => 'us']]
    2 Z$ x1 O8 _/ N( M1 F* ?! Q
  4. );; G- t4 {2 i! h' Z; G
  5. $updateResult = $collection->updateMany(
    " j  u6 k  R' j9 o( g
  6.     ['state' => 'ny'],
    , D* R* ~0 [$ g/ }/ u! n+ c
  7.     ['$set' => ['country' => 'us']]5 w5 m) S( q: N8 T# O- O
  8. );' R/ R( \% ]) A$ }% I8 ^6 F" r% y8 ]
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • - v7 }7 J' |$ T# Z5 N4 `9 Y2 @
  1. $cursor = $collection->find($condition, [7 L, ^7 `4 R2 }5 t& z% v" R
  2.     'name' => true//指定字段5 f* o- x1 e  `: }& _4 Y0 A$ z
  3. ]);
    ( i- b$ I% M- ~8 |. v* O; X% U! J
  4. $cursor->skip(5);
    " c" |- s% u: ~3 N; t5 D" w
  5. $cursor->limit(5);( F% ]2 I4 a8 `6 n- K
  6. $cursor->sort([" T* m0 [1 _% U; A
  7.     'time' => -16 R, q; E. g$ k( @
  8. ]);
复制代码

  •   o& d% r: ]! d; q! C! r- B0 B$ H, u
  1. $cursor = $collection->find($condition, [  W. @8 q  f8 [8 L! J( e
  2.     'skip' => 5,) P1 |/ ^0 N* o. a
  3.     'limit' => 5,
    % Z. ^! {3 p; X6 i$ k/ J* J, J
  4.     'sort' => [5 d' q: J1 @# }4 f9 U
  5.         'time' => -1
    6 \  x% f' m. H) B- H# Y" b
  6.     ],//排序
    # W* |+ m) `7 r% k1 B) r- I
  7.     'projection' => [+ B0 g4 m! f% h
  8.         'name' => 1//指定字段; |2 \, G$ B  z# L( C
  9.     ]& w4 Z( o8 J7 H  v
  10. ]);
复制代码
5.删除
  • 0 N8 B$ {- H* Y
  1. $collention->remove($condition, [+ E: ^0 e. l! X9 i$ I1 |( C, O
  2.     'justOne' => false//删单条3 @2 c1 l/ M, A, C& `+ {
  3. ]);$ p  i8 j9 f2 ^/ c
  4. $collention->remove([]);//删所有
复制代码

  • ) V0 m1 ?- g. S* ?9 W$ b3 |2 E2 M
  1. $result = $collention->deleteOne($condition, $options);
    9 i- x: W' D0 b' q* @
  2. $collention->deleteMany($condition, $options);
    0 `1 K) d% T/ _* b: {# l! t

  3.   |: h9 e( ?' p$ `
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    ' A6 w# c# R* v( U$ D
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键. A5 ?# S6 l( Y+ R! |/ o
  3. ], [
    - s% ~8 u4 z6 T( r( r0 Q; t
  4.     '$inc' => ['id' => 1]//自增
    7 f) i- x, I$ N
  5. ], [$ ~% b9 ?$ P& K1 r1 q8 n
  6.     '_id' => 0
    8 Q+ p& l# H2 O6 c' A* o
  7. ], [
    0 p+ G# l( W* j# r) x% a
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    9 A8 l% U* k0 ]
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    + s' I8 i- T9 R5 G
  2.     '_id' => $tableName. {, R1 @+ Z* O( ~% m
  3. ], [
    * J. b( E8 Z$ B/ I( B, z* A# F
  4.     '$inc' => ['id' => 1]- \5 V  X# C: p" t' h  ^3 N/ d
  5. ], [% I4 V# e. r5 Z" |$ O
  6.     'projection' => ['id' => 1],! P* c! ?# b! Y; g* O/ k. @$ ]
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    - x- _- W3 \: x' P4 U% J
  8. ]);
复制代码
9 G: `3 U1 r* P- |, t8 b5 U9 D9 I

. F7 m% S+ _6 Y1 ~
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 13:38 , Processed in 0.052146 second(s), 19 queries .

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