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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11540|回复: 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
      D! G& _3 v7 T1 Q. ]# E

  2. 7 G' g2 K: Q3 |6 h* h( E# [' v5 h3 V
  3. use MongoDB\Driver\Manager;
    ( I1 L) f0 M% O0 M- |0 P4 s/ P
  4. use MongoDB\Driver\BulkWrite;* T" I; B0 ^( B5 E9 s
  5. use MongoDB\Driver\WriteConcern;$ s7 ], a$ P& }8 a, \* [
  6. use MongoDB\Driver\Query;( I4 e/ V, g' ], Z
  7. use MongoDB\Driver\Command;
    & }7 l& {+ X( l' x' d

  8. 4 B. @# Y5 f" ?6 }) I) i* @
  9. class MongoDb {
    ! e4 _2 P) s( M& V& U, b( H! F
  10. : i  R! G4 r) i+ N; ~3 q
  11.     protected $mongodb;
    & J: T' h6 `/ H$ a: E( ~
  12.     protected $database;; R9 ~' h3 l4 A' m# y' W
  13.     protected $collection;
    7 |& P- S4 B9 u' c. Y
  14.     protected $bulk;
    & K  Y; X  V# ^( x# [! V
  15.     protected $writeConcern;
    - `% I2 g  g1 |8 m/ i( X
  16.     protected $defaultConfig
    $ K1 [/ V, x' H3 Y
  17.         = [+ G0 R9 G/ _9 H5 t/ V
  18.             'hostname' => 'localhost',
    , @6 |4 o- |8 T4 l& J) j/ Q) X
  19.             'port' => '27017',
    2 X* {/ ?, n9 Y* X2 w+ N
  20.             'username' => '',
    ! p8 \* y! F6 c0 m: g) ?. s! y
  21.             'password' => '',4 |9 q4 k  C2 {
  22.             'database' => 'test'
    ( P8 S, R+ A8 D
  23.         ];
    9 U$ u* T6 L6 w; Z# Z7 }9 V
  24. 0 A8 K3 ~& s* A! g
  25.     public function __construct($config) {
    : f) H: o1 t! l# P- k& v. W$ q; _
  26.         $config = array_merge($this->defaultConfig, $config);
    / a4 w, V& Q. i/ Q2 J' H2 ^
  27.         $mongoServer = "mongodb://";1 q% C/ _& D% K3 B( ~! L- `, A6 r
  28.         if ($config['username']) {- U- a0 ~3 B- H$ q# A3 D
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';4 k. j$ X2 P0 [7 y, }
  30.         }" R3 k9 j0 J* V, M. |0 T# e
  31.         $mongoServer .= $config['hostname'];
    + e9 `0 K! p4 P- @* H0 R8 ?* z. {
  32.         if ($config['port']) {
    ( \8 h* x; m+ D# k6 t; `
  33.             $mongoServer .= ':' . $config['port'];
    ( R. B! L% R  d% S/ ?2 [
  34.         }; M( U* g- V* M: ?8 x" K
  35.         $mongoServer .= '/' . $config['database'];
    1 F) a! H+ v* Y; f7 P1 B( Z
  36. ! `: p: ?0 n. l( G( K
  37.         $this->mongodb = new Manager($mongoServer);9 {; I  {# i  J+ Q7 `8 y
  38.         $this->database = $config['database'];! Y* u! w- |- D; x- D  I
  39.         $this->collection = $config['collection'];2 l5 |4 S$ |. l) o- E. l* g% [2 E/ G; c
  40.         $this->bulk = new BulkWrite();9 o" `. r9 j9 Q% F5 x! f' ]
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    0 \* x6 u  S# A
  42.     }" a6 ~- \( O! i- M# c& ?
  43. ' Q- I( P8 n8 C) f$ O& a
  44.     public function query($where = [], $option = []) {; a8 s' Q0 q9 y9 J0 k% g
  45.         $query = new Query($where, $option);
    ' v, G; o& g% V4 F. L
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);8 v3 J  I, A' N3 B9 @: }2 I) b
  47. " ]- f, ^9 b3 c- S
  48.         return json_encode($result);. Y$ [3 d) l2 h( S/ F3 _9 n8 E" B
  49.     }0 S5 C# a. }( B$ W! P. C
  50. 7 r# n* W1 }# D3 z
  51.     public function count($where = []) {
    3 j" K1 R6 ]" q) W  P6 {4 b3 r
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    / Q; _# s# b+ p8 [
  53.         $result = $this->mongodb->executeCommand($this->database, $command);% [& o) ~2 H- O, m
  54.         $res = $result->toArray();  K& g" O. w" A  c5 R; b& ]) k
  55.         $count = 0;! O4 v& D/ |  z/ p1 |
  56.         if ($res) {
    : G+ @' ^, @! d; y: A, v" ?
  57.             $count = $res[0]->n;7 m- b7 o& W, H+ E- x, u3 N6 ~. W
  58.         }  D0 `/ G+ I( a: P; t" ~7 J3 P$ {& s) s& m
  59. ! k! N* z, d( J9 n8 |# U
  60.         return $count;
    1 ~0 [6 w; G. q
  61.     }( D7 D  u! a& M* J7 U  s5 j  ]
  62. 7 _+ U( {4 M) X: N( c
  63.     public function update($where = [], $update = [], $upsert = false) {
    - ~5 [. \. o$ f3 b5 |
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    + S( S0 H5 o% M+ `; d( b
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);6 R4 I. T# _8 b. a; @

  66. " V# ^7 f8 P/ y1 h& j& e
  67.         return $result->getModifiedCount();
    5 j; C7 `- F0 O5 o% U9 U
  68.     }) g$ b3 a6 p0 A  @

  69. 2 B* ?' K' h2 Y% R4 T- R
  70.     public function insert($data = []) {. i, Z: }  ~0 J# a& O$ B" D& L
  71.         $this->bulk->insert($data);, B0 h3 T: A9 `
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);  N* j) m" W' h* O$ C$ a) ]$ a
  73. $ w, v/ D$ R" j; {% i
  74.         return $result->getInsertedCount();( @/ }6 d+ x4 a* e
  75.     }1 P: m7 f9 c. ?6 O! [

  76. # Z4 o5 t6 R' j" E
  77.     public function delete($where = [], $limit = 1) {! s4 b$ X& n7 o# z
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    . B& w) \- ~% V, B% p/ m
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    8 j) M+ T6 }: l- p; P
  80. 6 U: m1 Y6 i' [5 C0 L
  81.         return $result->getDeletedCount();
    . @0 V) N5 h! C; c% w2 e, |
  82.     }' {. n! V$ a  j6 ~8 B
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • " y$ \, w) B; q1 {
  1. new MongoClient();
复制代码

  • ! c8 H+ Y7 W- c0 @% {; i
  1. new MongoDB\Client();
复制代码
2.新增

  • 6 k& ], I+ }* Y3 f/ R
  1. $collention->insert($array, $options);
复制代码
  • 8 I1 G& t  D6 R, C; Y" e
  1. $resultOne = $collention->insertOne($array, $options);//单. z* S% |6 }2 _; R  `/ F6 x
  2. $lastId = $resultOne->getInsertedId();
    ( [$ N8 h" {, h* P
  3. $resultMany = $collention->insertMany($array, $options);//多+ c9 z# |1 B; f2 t5 s" B. v6 Z' A
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • & T( y9 Y- V7 m! l- s; h( r
  1. $collention->update($condition, [
    # P" p+ ]1 I2 C
  2.     '$set' => $values% K: [' v2 M- T2 R, o
  3. ,[$ E# Q" K, X! D7 l* F( S
  4.     'multiple' => true//多条,单条false! u1 q9 h# Y9 l
  5. ]);
复制代码
  • $ L6 p0 e* a5 B- a0 \! J
  1. $collection->updateOne(
    - E" r' _5 Q7 y
  2.     ['state' => 'ny']," z+ _- Q) n  v- x; B- p
  3.     ['$set' => ['country' => 'us']]
    % h) v. I% k: v3 W
  4. );& y3 E6 g3 ]0 ?5 \8 Y5 `
  5. $updateResult = $collection->updateMany($ E; d2 g) @* M" q& E& W5 @: S
  6.     ['state' => 'ny'],5 Q9 a9 Y4 X, s0 T' @* ^- ?/ [/ Y0 b
  7.     ['$set' => ['country' => 'us']]
    / a8 w* A' `* Z% Q/ n
  8. );
    ) G# Y- A8 r& d0 W% q. D  T5 ^$ z
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • " Y5 r+ ~1 T! ~( W# N2 w
  1. $cursor = $collection->find($condition, [
    " k4 y8 C9 ?' {5 ^8 @! {) a
  2.     'name' => true//指定字段* Z" `5 R5 |. Y9 [1 _1 J
  3. ]);& ]4 Q/ p' x- s7 y% J' c* r
  4. $cursor->skip(5);) V- i9 q" l( E
  5. $cursor->limit(5);0 q+ e/ d) _* ?! [
  6. $cursor->sort([0 L+ w& j# b+ O: B# ?5 W& T
  7.     'time' => -13 L$ _: }2 J- [8 k* _
  8. ]);
复制代码
  • " x; S1 O5 i7 n  r& N
  1. $cursor = $collection->find($condition, [
    2 h; w, N. C0 O3 _4 D# e
  2.     'skip' => 5,3 m  B  C2 H% A2 L
  3.     'limit' => 5,
    6 @+ H( k4 h0 ]$ m0 j* \4 w. M# ?
  4.     'sort' => [
    1 w9 ^8 a5 q, S. i
  5.         'time' => -17 r6 \$ D9 i( |% Z. i
  6.     ],//排序. E3 @$ J% M; w/ z$ W* w6 D
  7.     'projection' => [
    9 \2 d$ q$ `/ j7 _; C
  8.         'name' => 1//指定字段
    * W2 Z! e/ N( [0 |  Q  i) i2 f
  9.     ]' m; s# W$ U: a9 ^  I3 L9 V
  10. ]);
复制代码
5.删除
  • + ~' t* j$ O) ~# e4 A1 C
  1. $collention->remove($condition, [# F7 g5 c: _0 R) a# A3 Z- g/ H
  2.     'justOne' => false//删单条
    # |/ `( u1 Q, c8 ]& ~3 _
  3. ]);
      q7 c$ u+ }! ?  t- u! M. ~1 o
  4. $collention->remove([]);//删所有
复制代码
  • 6 q, K8 y* t) {) Y3 J& }
  1. $result = $collention->deleteOne($condition, $options);
    : ]  n% h9 {6 H' p
  2. $collention->deleteMany($condition, $options);$ j' y) d# n, Q, s+ y7 H5 q2 P$ r. T
  3. 4 }, G( G! [4 U& c4 \) p; R- W
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([+ `! I2 r: q( K% h* y! g8 n
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    , X) c# M. w, T9 r: U1 L7 M
  3. ], [4 e- C& l1 d$ z1 O4 d* ?
  4.     '$inc' => ['id' => 1]//自增4 m4 K$ G2 }5 r0 N4 O
  5. ], [
    9 d  I# V8 C) H, Y; M
  6.     '_id' => 0
    $ u% A- y. N0 P8 G% @5 v; Y
  7. ], [$ K. m' D# q9 e* }6 v- N
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    $ O, {: f' M, k, P$ W' B: g7 \
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    2 }( b  [4 b, q; s' |2 _( H
  2.     '_id' => $tableName
    : H9 c# n0 m5 h
  3. ], [
    # u! j* [/ }) C5 [$ p# A
  4.     '$inc' => ['id' => 1]
    $ \5 K& Q8 s1 y
  5. ], [3 v7 J0 s/ u0 u  R
  6.     'projection' => ['id' => 1],, l! t: n  j  z& g  `5 ]
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER6 F& i, {. v* ]$ T
  8. ]);
复制代码
0 u( N: Z5 S- L$ N; m8 d( |

. D0 ?  n6 s5 R* J' [' [3 `
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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