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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 17656|回复: 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
    : `; `. h/ t; j2 N7 s! ?) @0 @
  2. , P" `2 A) Y. M# c0 t
  3. use MongoDB\Driver\Manager;
    ' z/ |5 E; H+ @/ T9 j5 i1 w+ S
  4. use MongoDB\Driver\BulkWrite;& l7 ]9 e& E5 @/ d
  5. use MongoDB\Driver\WriteConcern;
    $ I+ r% o7 J, Q$ M, u) `& x
  6. use MongoDB\Driver\Query;
    4 D& J3 {) M+ }% `# Q- U
  7. use MongoDB\Driver\Command;# [3 T5 M2 d4 R/ }- S
  8. & E6 S: B' r, @% q) G7 J- ^
  9. class MongoDb {0 B; R' t8 _5 B( e. q
  10. 7 o  u* _+ r3 t# n$ @6 v1 N' v" }
  11.     protected $mongodb;9 D9 _, h/ o  Y8 Q
  12.     protected $database;
    2 R- _7 D4 p( f8 R7 o) {- E4 J
  13.     protected $collection;
    : h; X* ^" `) |5 q
  14.     protected $bulk;. T5 T4 R8 H3 e* r6 y; @
  15.     protected $writeConcern;
    / e8 O( X! Y1 d3 W* U, J, E
  16.     protected $defaultConfig
    % y: I; i9 p: t( o7 `
  17.         = [0 X; t. ^+ g7 I, B, F0 l% I
  18.             'hostname' => 'localhost',
      V; P4 I  M0 f* A" y: T
  19.             'port' => '27017',# l% P5 T+ F. h3 S# y$ L7 h' h4 f, d
  20.             'username' => '',1 W# `% q6 i5 S2 }/ d! F  P
  21.             'password' => '',
    - c4 \# r8 a% Q
  22.             'database' => 'test'+ j7 |  ^9 O; q) M1 r
  23.         ];9 c: V# _) `9 b
  24.   p9 k+ }! E  T3 [3 b
  25.     public function __construct($config) {
    ; w/ [. }, r9 [/ I4 K  f
  26.         $config = array_merge($this->defaultConfig, $config);, C/ `' Q+ u; l- m$ O4 [3 r: T
  27.         $mongoServer = "mongodb://";
    $ W& _. B* }3 m- w: q: P7 D' R
  28.         if ($config['username']) {
      {; i! ~3 n- W. o/ X, ?" Y
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    ) [* ~, z/ Y) i% H4 c$ D
  30.         }4 O' S& \2 E) I7 B* s* L( d
  31.         $mongoServer .= $config['hostname'];4 \) `0 p/ C5 ]2 A8 K1 t
  32.         if ($config['port']) {0 G" M9 Z  c% ~6 N
  33.             $mongoServer .= ':' . $config['port'];
    6 D6 @! Z, m$ \8 y& C+ `5 V# c
  34.         }) z/ e' ?; ~# P$ F0 @+ V
  35.         $mongoServer .= '/' . $config['database'];
    * x; P* \- e8 G. R* I
  36. ' f) l# L4 f4 Z; Q2 @# J# F) C2 t
  37.         $this->mongodb = new Manager($mongoServer);
    6 z* a) ]) \  h! y; G, n- E
  38.         $this->database = $config['database'];
    - f5 H5 R  V+ E' z0 V
  39.         $this->collection = $config['collection'];1 U% Z  K) i( U
  40.         $this->bulk = new BulkWrite();
    : A0 ~) V* X; M4 V" G- Z/ {
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    & b1 B( V' t8 L; X4 L
  42.     }$ w) |, {' V/ |9 }0 D6 l8 K
  43. ' U3 q" H# q% I2 `: @; T
  44.     public function query($where = [], $option = []) {
    : j) u3 i$ K- [: R
  45.         $query = new Query($where, $option);
    , a2 b+ @* w$ w8 J, d; P
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);: m+ {- B, z# b7 ^( A- z( T' E
  47. 0 g* t0 j. Q# U2 l
  48.         return json_encode($result);
    " ~. s0 z( t7 c2 B: `
  49.     }2 J9 |9 S; F" h" s' W

  50.   U$ |5 v* l/ d# g
  51.     public function count($where = []) {- G9 J6 c. m2 u' A. |1 P. y% I
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);9 }: V% d$ X- Q* b
  53.         $result = $this->mongodb->executeCommand($this->database, $command);0 I- P' o5 {1 Y6 O) f! B- a
  54.         $res = $result->toArray();" T* o, H" @, I0 g
  55.         $count = 0;
    + n$ j: a7 I( m& _
  56.         if ($res) {
    & F, x9 V# z* D! q1 E0 I1 `
  57.             $count = $res[0]->n;
    % b; E" Y/ k! j- L$ r
  58.         }: |& Y& n# t+ O8 x( I
  59. 7 O* z/ t/ P  l* W1 c/ D
  60.         return $count;; W. Z/ z( b4 s1 I' [) u
  61.     }
    : p& |6 B* G7 Y/ V

  62. $ Y% a" B6 {9 j& ~( ?
  63.     public function update($where = [], $update = [], $upsert = false) {
    ( m9 j$ z  r; i
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    1 C$ Q3 l& q: x
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    - k- M3 K% e' h- L% ^: g
  66. % f5 ?- R, O, @
  67.         return $result->getModifiedCount();4 O4 Q' ]/ P; M* o" i  j
  68.     }
    8 ]- F  S# K  x! N& u/ }: I1 o
  69. " D5 C  a' G( N( f* H- d
  70.     public function insert($data = []) {
    6 Z6 J' d1 C0 ]* N' r) i4 I/ E
  71.         $this->bulk->insert($data);$ u+ _* C! s8 Q* C" Y5 ~
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    5 }% u$ V) j& Z; I5 F# d9 c; l
  73. 5 H+ U" ~0 R1 t
  74.         return $result->getInsertedCount();! b% z$ U9 m- x
  75.     }
    ' L1 n' ~0 ?3 }  s

  76. + u& q  q. ^( M6 s- a9 g
  77.     public function delete($where = [], $limit = 1) {4 A0 M2 E1 S+ l
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    + t! C5 ^4 Z, o+ l
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    . J. ^  |% u# R- O
  80. 7 v" G4 Q( J3 z; F; U  n% ]: i9 a
  81.         return $result->getDeletedCount();: D' C; T; M" ~9 T$ G
  82.     }
    9 M) B+ A, S1 I8 `
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • * Y; ?7 G4 ~5 v7 i' {' u
  1. new MongoClient();
复制代码

  • : H  W* ]/ W0 p0 n0 m5 U- a; J
  1. new MongoDB\Client();
复制代码
2.新增
  • 7 I9 u) i* w6 \$ o0 G& y2 c6 U
  1. $collention->insert($array, $options);
复制代码

  • 3 Y$ k* a+ s" C- v! x
  1. $resultOne = $collention->insertOne($array, $options);//单
    7 }% F1 e+ O% H; ~8 P' D( p
  2. $lastId = $resultOne->getInsertedId();
    $ N6 `7 C$ X1 A, E8 k1 p/ i+ A# o
  3. $resultMany = $collention->insertMany($array, $options);//多; F' J+ u0 b( b* H  Q& z
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • . h8 E( o; m7 n3 i5 L
  1. $collention->update($condition, [
    % H4 L! S0 J$ T7 }
  2.     '$set' => $values# U4 K2 ]( j. |9 ?2 J, _! [
  3. ,[
    2 w. t7 H! Z2 e: a; Y$ Q
  4.     'multiple' => true//多条,单条false5 ^, |9 U' \; D' J5 X" Z+ T4 H
  5. ]);
复制代码
  • 9 T) ^, C+ @5 h
  1. $collection->updateOne(
    - L: I0 ^# s2 }  P5 F4 L
  2.     ['state' => 'ny'],2 D  T, D$ ~- o" ]% H
  3.     ['$set' => ['country' => 'us']]
    7 u6 r3 r1 c$ R4 ~- W
  4. );% J( E5 q  D& m
  5. $updateResult = $collection->updateMany(
    . R4 {0 Y1 u. R# X  W/ e+ U
  6.     ['state' => 'ny'],6 m" r. `, P/ u) |5 e
  7.     ['$set' => ['country' => 'us']]
    7 d5 w. Y" @% b8 |' p% B
  8. );
    ) i/ d! ?( v. D( W! U
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询
  • ( I3 n5 ~1 O$ d  m  C/ U+ G1 Q' m9 F
  1. $cursor = $collection->find($condition, [4 \, {% k- C! C# u0 @$ I
  2.     'name' => true//指定字段" ~5 m' X8 }5 p2 N2 R2 w
  3. ]);
    3 u5 p# Z) [9 {  p" r5 |
  4. $cursor->skip(5);
    " W0 f5 O" r) }
  5. $cursor->limit(5);8 O. Q4 b5 B; {, Y
  6. $cursor->sort([2 V& u/ I% B1 A$ V# H3 F
  7.     'time' => -1" m) w) i& E2 D8 ?- ^$ X5 O
  8. ]);
复制代码
  • 2 P/ O4 C, X0 a, F0 Y1 \
  1. $cursor = $collection->find($condition, [
    ' E1 \9 V1 v: R# r: {
  2.     'skip' => 5,
      l, ?; C* Q+ R- K3 F7 T: H% o
  3.     'limit' => 5,
    $ k4 u4 E" i0 V9 [9 P
  4.     'sort' => [
    0 s2 e6 ^. ?6 C
  5.         'time' => -1) N2 R$ c& i% O: e
  6.     ],//排序- n+ I2 t1 Z- T  V  ~3 g% T3 G
  7.     'projection' => [6 M+ s8 G. ~% _0 [( g
  8.         'name' => 1//指定字段4 T/ U: O8 b( c' R" [
  9.     ]
    0 }. x* k$ q: f7 m" }0 Z  w) E
  10. ]);
复制代码
5.删除
  • : K2 V' q( O! T4 j* m% q
  1. $collention->remove($condition, [3 |! t. F8 Y& a) N
  2.     'justOne' => false//删单条; q8 i2 y* q& d0 Y
  3. ]);
    ' R! I5 V. W  E5 Q) I1 X. @
  4. $collention->remove([]);//删所有
复制代码
  • 3 A/ S0 p3 G' r% L5 \; i/ G
  1. $result = $collention->deleteOne($condition, $options);8 J2 z" M  H; b. ]
  2. $collention->deleteMany($condition, $options);- ]' [1 ~# K. `( D9 `- t! d
  3. 3 L3 `) u! C8 X) u
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([3 {5 J! W+ R. t( {- v
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    5 Z; e# D. g7 b
  3. ], [- y% w- S9 A: K- H
  4.     '$inc' => ['id' => 1]//自增
    ! k* S1 Y( Q, R. c3 D! g" y
  5. ], [5 n- y$ N' {3 I, }  Q) h1 l7 i1 e
  6.     '_id' => 0
    - i' }4 M) n' y/ {! O+ ~5 O
  7. ], [" ~$ |8 W3 X; f5 g. E
  8.     'new' => 1//返回修改后的结果,默认是修改前的' T/ ]9 Q+ E5 N' P
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([0 m, t6 Y" R# |5 s
  2.     '_id' => $tableName
    8 q) F! h  k/ V6 S) r
  3. ], [' C! U; X6 a# }
  4.     '$inc' => ['id' => 1]* n- G- n. _% ]. g# x# X
  5. ], [
    ) n, T: ^* t& a, L1 s0 e
  6.     'projection' => ['id' => 1],
    6 S8 V# n! T0 Z2 J
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    & L5 h+ Y+ R. w7 C7 x, ]
  8. ]);
复制代码
# Z4 R2 f' W8 Y* r% n+ W

4 s  }% ]- T0 d2 K# C' k$ O
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-9-22 04:12 , Processed in 0.054997 second(s), 19 queries .

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