cncml手绘网

标题: 升级PHP7操作MongoDB [打印本页]

作者: admin    时间: 2019-3-19 14:24
标题: 升级PHP7操作MongoDB
使用 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
    . }! x9 W, i% j8 D* s; I
  2. : [( H" L% R, `
  3. use MongoDB\Driver\Manager;/ g) h4 B- s& {5 L' j2 k6 c4 f
  4. use MongoDB\Driver\BulkWrite;% W# O& W3 b* D' ]+ s) T3 f# B
  5. use MongoDB\Driver\WriteConcern;8 P) ^, k( R. c5 s
  6. use MongoDB\Driver\Query;
    ) p7 D, Z4 q& r6 A
  7. use MongoDB\Driver\Command;
    + ^$ j; E3 i) E& T- A
  8. 1 |* N4 h$ {( Z  }! o
  9. class MongoDb {& B( C5 U- x$ M; y5 t( m! d
  10. 2 y( g$ c# `9 ^* g
  11.     protected $mongodb;9 ~4 k8 R) F+ F
  12.     protected $database;2 \6 a$ }' D$ t) {7 P/ d
  13.     protected $collection;2 g) ~) n/ l; {) A0 q6 p
  14.     protected $bulk;
    ! w( \$ o1 |5 w: T0 F$ v! L/ h  X
  15.     protected $writeConcern;# D# Y' s9 \" K8 h* f- ~* V
  16.     protected $defaultConfig
    & F5 ~# e- ?! h
  17.         = [
    7 e8 t( W2 f+ d
  18.             'hostname' => 'localhost',
    $ p/ i# M& P1 q8 S
  19.             'port' => '27017',1 g0 N+ N. [2 G
  20.             'username' => '',
    / e% n6 L2 F2 a) I+ x
  21.             'password' => '',1 ?0 w( f3 g" b7 u
  22.             'database' => 'test'5 @# `  F$ g! o+ K- E
  23.         ];2 n: t# |2 L3 N; U0 [
  24. 5 I, k8 s+ Z6 C; Z( }( r+ U
  25.     public function __construct($config) {" n# z' b) F% O* E1 B) m3 e0 L- y& z
  26.         $config = array_merge($this->defaultConfig, $config);
    $ `, y) g9 {5 O6 {" M
  27.         $mongoServer = "mongodb://";5 v: s7 d, s% d5 c7 ]% M: _
  28.         if ($config['username']) {$ I% i3 |! T9 K' f
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';: W5 ]2 E5 g. V) q2 b2 c
  30.         }
    " g! |( K- ?0 t3 t
  31.         $mongoServer .= $config['hostname'];, ~4 N* i+ ~5 i! n7 p7 |
  32.         if ($config['port']) {/ P" n) [2 b; V' Q, `
  33.             $mongoServer .= ':' . $config['port'];
    , U- D1 t$ T2 j# Q
  34.         }
    & @: K, X" B2 e
  35.         $mongoServer .= '/' . $config['database'];
    ) f' u% o6 f/ R$ L; c
  36. $ ?- K2 r6 w& Z
  37.         $this->mongodb = new Manager($mongoServer);# }3 \9 {: G! O! F2 X
  38.         $this->database = $config['database'];( s! R8 `- K3 H4 q& K
  39.         $this->collection = $config['collection'];# L0 z4 ?1 Q: Z$ E: n) I; U8 l
  40.         $this->bulk = new BulkWrite();2 i5 r3 d7 |) C5 e
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    + E  A, J$ C" ?3 d) P
  42.     }
    2 U6 D; @/ P7 V/ J5 L  w; I

  43. . e8 h, ~1 J1 x; x8 X
  44.     public function query($where = [], $option = []) {
    - S/ c$ V* s" G$ _
  45.         $query = new Query($where, $option);# l, V! P$ F6 i0 S( p0 T
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    " U/ X3 t# A& j$ {9 z6 e4 _
  47. . d8 I; O& Z$ Q1 G
  48.         return json_encode($result);
    5 n. C9 V( I1 F7 A' d
  49.     }- E3 |- j0 N2 P# `
  50. & y. j5 c# U, ~3 B; S
  51.     public function count($where = []) {& w& Q0 C! @( f) o0 }$ @/ D
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    2 y3 a0 P6 @1 E9 C  ?  B+ k
  53.         $result = $this->mongodb->executeCommand($this->database, $command);6 h+ H6 u: a$ `5 G) \) K
  54.         $res = $result->toArray();
    7 c+ N) t5 I4 \# l# b3 ]; f# s
  55.         $count = 0;% x8 X# O. X: r6 z$ u
  56.         if ($res) {3 a* H( Q4 R: [; Q$ w. y% v1 ^
  57.             $count = $res[0]->n;
    ( X. V' d9 q2 Y* u, {
  58.         }
    0 b9 B2 `2 a0 k( f9 O. e
  59. # X7 F* N$ \+ _4 t
  60.         return $count;
    & A4 ~: v4 d" H) J2 X9 _( x
  61.     }/ I& u, x8 Z; r: e) P) n& m; T

  62. 4 [. Q& ^6 x5 I: S
  63.     public function update($where = [], $update = [], $upsert = false) {6 m" i, s& f* l& Y
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    / l, A! f  I* W+ d
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);3 r) p; N$ T0 {  v
  66.   o& P' d4 X+ ~3 O
  67.         return $result->getModifiedCount();2 _$ Z9 w" w8 e- K2 g
  68.     }$ `9 c2 H) `, S$ a$ J- W: [. T8 L
  69. . C" i. a, U; N( `% g4 U6 N5 f0 @
  70.     public function insert($data = []) {
    - s6 ?% S( p5 p$ O$ M6 k( W; Q3 j
  71.         $this->bulk->insert($data);
    * R. X# q$ h3 R  j' z( E
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    2 y+ X/ y2 u( c1 K& x3 i3 F

  73. ; U9 @9 T* H" M
  74.         return $result->getInsertedCount();: T$ M8 l0 d3 `% s  d/ V
  75.     }
    " {4 V* {% D& L& C

  76. 9 M7 T) z9 c0 Z1 M! w
  77.     public function delete($where = [], $limit = 1) {; h8 I- Z$ P& }' N
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    3 _! c, P% i0 r1 S* s" I/ p
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ' M! n. W7 F/ E

  80. ! i% o: T7 ^( ]7 R) E. H
  81.         return $result->getDeletedCount();
    / d, C  k# O4 S' A
  82.     }1 E- [. O: [8 _' }, g2 u
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  1. new MongoClient();
复制代码
  1. new MongoDB\Client();
复制代码
2.新增
  1. $collention->insert($array, $options);
复制代码
  1. $resultOne = $collention->insertOne($array, $options);//单
    & b' _9 x* U$ [
  2. $lastId = $resultOne->getInsertedId();5 Y  \! {0 Q; F3 t7 t
  3. $resultMany = $collention->insertMany($array, $options);//多* W& b1 F8 s# C! V
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  1. $collention->update($condition, [
    0 N7 V6 s! f  J6 u) B$ D! c" m8 L
  2.     '$set' => $values
    ! ]( z8 r5 n/ B% I7 Z$ a
  3. ,[1 Q+ t$ k2 ?2 M  K
  4.     'multiple' => true//多条,单条false5 w; B6 d4 P: V
  5. ]);
复制代码
  1. $collection->updateOne(3 E' e: `. G% q
  2.     ['state' => 'ny'],
    , E$ V0 j* d. Z2 J2 p0 {" {
  3.     ['$set' => ['country' => 'us']]
    + n) w) t# H7 o- u3 h
  4. );
    4 @+ ]0 c- m  o0 y' x7 @
  5. $updateResult = $collection->updateMany(
    0 |0 `9 o( W; J$ q) p/ y
  6.     ['state' => 'ny'],
    4 \  Y. p* @) J
  7.     ['$set' => ['country' => 'us']]
    3 \% c9 f+ {7 e( [$ V  y) t
  8. );) b2 p: B( w/ @1 @
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询
  1. $cursor = $collection->find($condition, [$ q3 c" t% J5 P% G' c& H
  2.     'name' => true//指定字段
      b/ Y  `. I9 P$ x- U
  3. ]);
    5 p7 x: k7 e6 Z% E5 B5 Q7 D
  4. $cursor->skip(5);
    + D& Y1 T! |6 M; ^  h
  5. $cursor->limit(5);
    / H' L& P  X! h! S6 r
  6. $cursor->sort([9 d0 U) c5 Y4 D! Q* O& @; X
  7.     'time' => -1) L9 |% ^3 W: `
  8. ]);
复制代码
  1. $cursor = $collection->find($condition, [) @: \5 d' F$ d% B) O
  2.     'skip' => 5,. R. X; Z9 \: z& f5 `) p
  3.     'limit' => 5,. D: H9 `, J  t; H* Z4 J
  4.     'sort' => [* U' c0 @* [( e9 j" T/ }3 P
  5.         'time' => -1
    # |4 x& Y3 i# E& p9 H' B$ ^
  6.     ],//排序* K$ Z0 l# m* N+ e1 a/ v
  7.     'projection' => [) i6 s" A3 |7 |6 k- a# r
  8.         'name' => 1//指定字段
    5 e& G+ f5 i+ F$ F5 g
  9.     ]
    7 t/ s" W2 t" i  _* c
  10. ]);
复制代码
5.删除
  1. $collention->remove($condition, [8 |6 r" a2 X5 q! ~, w* o0 Q
  2.     'justOne' => false//删单条. z* M( Y2 ?5 \8 p; ]+ v% ^
  3. ]);, g& `9 m3 e9 a/ I- w
  4. $collention->remove([]);//删所有
复制代码
  1. $result = $collention->deleteOne($condition, $options);2 T4 D8 @: L# d4 J
  2. $collention->deleteMany($condition, $options);
    , V+ A, S0 X) B
  3. & `5 ]* K$ @' z. Y' B& u9 w
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    9 Y9 B- w* e5 W5 g9 u
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键& l; ~6 z4 H* D
  3. ], [( T+ w) c# G$ u# _9 k5 z+ p4 K
  4.     '$inc' => ['id' => 1]//自增
    9 i. X: ]* r6 M2 D5 U
  5. ], [! s9 m- W- |6 z0 s% I
  6.     '_id' => 0
    ! `6 e* }$ K% t* A/ J4 W
  7. ], [/ i& e0 C" P: \$ p# l% f+ |
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    / L0 @1 R' s) H% u1 @! o' V1 c  X
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    , c3 D# q# h0 Q7 e% L( ^( }
  2.     '_id' => $tableName
    3 D+ A, k  ]: p( V( F
  3. ], [
      Y! r" ?% h0 W: V
  4.     '$inc' => ['id' => 1]
    ! K, ?% A5 f1 O" v2 X8 s2 r. s; j
  5. ], [
    ' D6 o5 `2 n7 J- x9 ]* F# l
  6.     'projection' => ['id' => 1],+ \. ^; {8 C+ N% f3 z; ~) |4 X
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER( ?  B! V- c* c
  8. ]);
复制代码
" `# p% M5 t( c' m/ B8 T
/ D1 D9 K8 I6 F5 b3 x1 [( ]





欢迎光临 cncml手绘网 (http://www.cncml.com/) Powered by Discuz! X3.2