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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11560|回复: 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
    . Z7 I- J; Q; N/ b% m; w
  2.   s8 \1 q! z6 n/ A
  3. use MongoDB\Driver\Manager;
    6 H9 e3 K2 f7 L5 c' Q5 j* l9 G
  4. use MongoDB\Driver\BulkWrite;
    / h& P: X( ^* G$ L0 Z4 o$ @& K
  5. use MongoDB\Driver\WriteConcern;9 ?, F3 Y# K- I+ i
  6. use MongoDB\Driver\Query;
    * m8 }$ Y! U' ?0 {( ]
  7. use MongoDB\Driver\Command;+ N+ \# U  Z+ e. n
  8.   _6 `" [4 V5 j
  9. class MongoDb {
    : X& y" B! P9 F! U  q: s4 Y

  10. 2 w) q8 B& \5 x5 r5 }
  11.     protected $mongodb;2 [7 h* n4 p+ @5 _
  12.     protected $database;2 t6 E, s4 \4 J$ e+ y4 e9 _& ~+ k* u
  13.     protected $collection;7 C+ n+ I9 n& @- O
  14.     protected $bulk;1 I# _. j' u- f: `
  15.     protected $writeConcern;  B4 Q6 W. k; q- W
  16.     protected $defaultConfig
    , k: \- K  L1 U" b: g- {5 a
  17.         = [
    + f, G( ?2 Y% ~8 i1 E0 R. h
  18.             'hostname' => 'localhost',* D5 L$ C1 J1 n4 Y
  19.             'port' => '27017',
    & Z9 A8 V+ o5 M, ^; @6 [6 y' t
  20.             'username' => '',3 i) q  X8 ?  A$ P1 U
  21.             'password' => '',
    4 j1 \" Z( H  b9 c: Z
  22.             'database' => 'test'
    ! @* m! r- W- n9 n2 B' ?
  23.         ];% A) W" N% E8 F8 f' A
  24. 1 }% n. N4 I: A8 n' h
  25.     public function __construct($config) {
    8 b; N8 j! k: Z4 U2 u  U
  26.         $config = array_merge($this->defaultConfig, $config);) \% e! \! s( Z9 h6 E  m$ _1 S" D
  27.         $mongoServer = "mongodb://";2 z. Z& f! A2 U( M$ ^) c
  28.         if ($config['username']) {& t" J$ K6 Q8 _6 `& k) M
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';5 k0 U) g6 A3 d+ ~# j: [
  30.         }
    6 x& |! G; ~/ v0 L& I
  31.         $mongoServer .= $config['hostname'];
    / D- F, P8 Y! H
  32.         if ($config['port']) {
    ( U5 n6 T  q. e
  33.             $mongoServer .= ':' . $config['port'];
    9 {8 T- B: y2 A4 ^
  34.         }
    7 _" X$ Z- t4 h4 U) j4 X1 p* o
  35.         $mongoServer .= '/' . $config['database'];
    * h7 z) n# h4 N2 U: S- o

  36. 1 w5 f4 m9 y1 e: z8 d, Y/ t9 ~, S# @! N
  37.         $this->mongodb = new Manager($mongoServer);
    7 V3 V9 v" g- m: _. h
  38.         $this->database = $config['database'];
    5 F" X% r3 ^' `: I5 A/ D. B+ {
  39.         $this->collection = $config['collection'];
    0 L; Q3 R5 Z" O+ ^/ o! `  E: n' a
  40.         $this->bulk = new BulkWrite();1 t/ y& T- r% y* x0 j3 M) ^
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);* j: |; s8 f( E0 J
  42.     }4 _, D  `0 G9 S" w
  43. 1 `  ~' @* [/ j0 y
  44.     public function query($where = [], $option = []) {
    + B# j; N3 U$ b
  45.         $query = new Query($where, $option);
    7 |# P1 X7 b. S8 {
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    8 d, i# P9 K* {) `1 `
  47. 2 u; P- P6 b8 t7 n. f1 O  |
  48.         return json_encode($result);6 a# E7 p9 f: f1 m' Y
  49.     }/ c. _- M' b6 `

  50. " r! P! u$ R4 J9 f
  51.     public function count($where = []) {
    ! u! Y$ z2 p" [3 s
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);. P" C3 w6 R% V1 K5 B9 h
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    ( Y% ~6 }" ]; d8 J. t
  54.         $res = $result->toArray();0 E# c) L0 U" {. _4 a+ ]5 \/ z% D
  55.         $count = 0;
    3 H+ M7 L. B( \& M* Z* Q  Q
  56.         if ($res) {
    8 U: \; a/ Z5 x( ^# o- Q
  57.             $count = $res[0]->n;
    " {/ h2 a: @2 L) h
  58.         }" v' @3 i. C5 a2 y8 r

  59. 1 Y5 c, I/ L! j* J4 S& q
  60.         return $count;
    % p0 z0 G3 I0 u) h2 f
  61.     }5 C: D9 ]. v9 w( b7 Q

  62. ( [% c1 U) q: Y/ q* h& g
  63.     public function update($where = [], $update = [], $upsert = false) {0 V" p" u% u; i6 S+ {, r
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);- B, G6 {1 c# ~% d
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);+ P7 k( o3 j$ ^6 n4 H4 R

  66. ) k! V  L2 S6 u
  67.         return $result->getModifiedCount();
    4 U4 ~% w6 b( e3 {! M6 p; |  M& j
  68.     }
    2 m" O7 P, ^) }  [' F9 f

  69. 0 Y6 ?* e5 h; i9 M1 |7 @, J
  70.     public function insert($data = []) {4 {% D, j2 y0 e( W
  71.         $this->bulk->insert($data);/ g' e( Z7 _# b# @6 W! c- g4 S  p
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);$ K6 k% M/ a6 B1 X0 }2 l! E* m% d

  73. 5 I7 s; r3 x( ]; H6 q& r
  74.         return $result->getInsertedCount();) ~' c0 I! S" V0 `
  75.     }
      X$ K  }0 `7 h$ x- w
  76. # f* O- V5 J$ T: [  _3 g/ z% m9 \! S
  77.     public function delete($where = [], $limit = 1) {
    # {2 r4 N: M* t$ x& x) `
  78.         $this->bulk->delete($where, ['limit' => $limit]);, a' C! S4 m9 Z' T# g9 q
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    , J: j1 Y" x  p3 d. u2 e7 s4 q

  80. ! f8 d2 y4 H( e
  81.         return $result->getDeletedCount();6 V8 |# E$ I1 x& [* \/ C
  82.     }& _* a/ v! w7 ], N/ Z9 G* P0 O; T
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • . I+ ~2 \3 P9 ^* f) v
  1. new MongoClient();
复制代码
  • ; O) ^0 h2 ?9 P, h3 {
  1. new MongoDB\Client();
复制代码
2.新增
  • * Z4 K, M- m/ {
  1. $collention->insert($array, $options);
复制代码
  • 1 H4 R; w# C% W2 ~" {4 a& C
  1. $resultOne = $collention->insertOne($array, $options);//单9 x0 ]& ~' i5 @+ m' v
  2. $lastId = $resultOne->getInsertedId();
    2 p, u* M4 Y2 C
  3. $resultMany = $collention->insertMany($array, $options);//多3 J5 Z& N/ X. K/ K
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • ' T8 c7 K) h0 p' G. F3 |
  1. $collention->update($condition, [# R. E  @; T3 J( M# B; |6 ]4 h# H. X
  2.     '$set' => $values) l  [. C, J5 q8 B* ~. D" k  v$ k! H
  3. ,[
    # D. v/ a/ I- o" `8 |( v& k
  4.     'multiple' => true//多条,单条false
    ' G/ w+ ^) t: G
  5. ]);
复制代码

  • * M6 k" \8 \" |
  1. $collection->updateOne(
    . w# G4 t0 `7 X  K
  2.     ['state' => 'ny'],
    ; f2 X: B7 s2 N* ?& N  g
  3.     ['$set' => ['country' => 'us']]
    , c7 Q9 Y$ S2 \7 \9 D
  4. );
    % R: O2 m  T' Z0 g; A$ X1 ~( a
  5. $updateResult = $collection->updateMany(7 }) e0 E* t9 ~7 t
  6.     ['state' => 'ny']," |( |' e! W- c) n5 }5 S2 W) s# B
  7.     ['$set' => ['country' => 'us']]
    $ q9 L/ A! J9 ?. }4 @' s
  8. );! d6 j6 I5 s- s
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • - D; G+ m  T' b4 x& M4 T; B  e
  1. $cursor = $collection->find($condition, [7 [* h. p) M  k. }1 H/ i% N4 `, k
  2.     'name' => true//指定字段1 S9 e' d) i$ u
  3. ]);+ k4 e) _: ?* q' f. u! M/ B
  4. $cursor->skip(5);# r; ~) Z9 C+ }$ Q, V7 g$ T
  5. $cursor->limit(5);+ \$ ~( s& i9 P4 ]$ M
  6. $cursor->sort([" l% E/ p- F6 {/ \) k/ l; [
  7.     'time' => -1
    7 g9 e4 A% D6 P# j% i. t0 A
  8. ]);
复制代码
  • " F( y% Z( D3 r* G9 P% ~
  1. $cursor = $collection->find($condition, [! X* F) H7 X) n; }
  2.     'skip' => 5,7 a" |% O0 B2 {* h: r  {: h8 h8 F) J
  3.     'limit' => 5,( t4 U( v0 [! K8 j
  4.     'sort' => [6 l7 s7 ~; }, [) i3 V1 y
  5.         'time' => -1
    $ J! s5 q: ]$ X2 }  c
  6.     ],//排序% g3 R5 l% c3 y
  7.     'projection' => [
    * x* t3 }; y0 T/ @! d
  8.         'name' => 1//指定字段
    8 `9 V. H2 z* _6 T% d1 Z
  9.     ]. O( G, G! g# |0 a* {& j
  10. ]);
复制代码
5.删除

  • : R5 {; U' y6 d0 f  y7 }
  1. $collention->remove($condition, [% \/ r( b* Z( O) n* t7 r
  2.     'justOne' => false//删单条! k% G$ I+ i$ W/ X5 ]( P
  3. ]);
    # w( p8 }! ^; Z# a4 j5 H! u6 X
  4. $collention->remove([]);//删所有
复制代码
  • 7 q' f" n( y. ^* l2 L8 N9 G
  1. $result = $collention->deleteOne($condition, $options);, p' m$ H/ X# h, b
  2. $collention->deleteMany($condition, $options);( f/ o+ S! k! g0 k7 E& J2 ?' R# F
  3. / T$ |6 |% x2 b% L" e6 c: V
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([4 D9 ^7 B; T6 Q
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键0 G. J4 m6 y- e) o
  3. ], [9 T* N5 F# S$ U/ q( {
  4.     '$inc' => ['id' => 1]//自增
    1 A( p7 G4 c6 ~( s2 u; C
  5. ], [$ k3 V( S. l+ w
  6.     '_id' => 02 ?3 f% t6 D: `0 ]5 _5 {+ m
  7. ], [) V) U  ^- e; `" F- e( F
  8.     'new' => 1//返回修改后的结果,默认是修改前的9 C8 A, |  e9 x. s; j
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([3 H1 ~! ^6 {7 ^4 U" I; K% ~
  2.     '_id' => $tableName: R! F! ]- U$ ~% D; U
  3. ], [
    4 l  F6 U  c2 V
  4.     '$inc' => ['id' => 1]
    2 @- ^' M' ?2 k8 f+ K, `) f' @- J
  5. ], [
    . _# r6 s5 d+ t+ R
  6.     'projection' => ['id' => 1],4 o8 P/ P. M6 o) v" D9 i) e1 O
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER8 J. I! q4 Y  L" [; y
  8. ]);
复制代码

/ w$ x7 _0 h+ u% B; y- I  L8 X/ n$ I
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-20 11:00 , Processed in 0.120497 second(s), 20 queries .

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