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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 17000|回复: 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
    7 C. q  A, \, s# o6 m. }) w5 s) o

  2.   G1 B' B( l- _
  3. use MongoDB\Driver\Manager;
    " z/ W3 W6 E4 U! q+ T: j3 L" s
  4. use MongoDB\Driver\BulkWrite;8 p0 J% p, C+ W  G
  5. use MongoDB\Driver\WriteConcern;* P+ t2 ~# K- k, I' ^' ~
  6. use MongoDB\Driver\Query;
    # u9 y' m2 W. ]9 W8 F
  7. use MongoDB\Driver\Command;" z: n9 _( ~* G

  8. 5 @% P6 o% G5 j# r- S" v7 M) O  c+ v
  9. class MongoDb {0 P9 L! E# \9 {. |+ k2 v( G5 Q
  10. 7 a% s$ t9 `: @/ v9 s5 X6 i4 ?2 U* }
  11.     protected $mongodb;" B, s" @6 g5 y( l3 h
  12.     protected $database;
    / g) R& v3 W- g% y+ K: x% [- y; }
  13.     protected $collection;
    ( u% ]" d6 T' r( ]! ~* ^
  14.     protected $bulk;0 k( {8 J+ ^: c2 ^7 l3 O4 a
  15.     protected $writeConcern;
    . r  L+ s# }7 i
  16.     protected $defaultConfig: H6 o* d5 i& ~) p$ d" a( N
  17.         = [9 H. M9 ~4 S; S. S
  18.             'hostname' => 'localhost',1 [/ r( H1 H3 I0 o, d, b2 T" ~
  19.             'port' => '27017',% f4 _. _8 _( b# o; A
  20.             'username' => '',; E2 E" T1 \7 r2 k$ q
  21.             'password' => '',* G+ n9 m& l+ R2 b& ]
  22.             'database' => 'test'7 x! D: d: O% H- ?: E
  23.         ];1 T1 |# i8 i, f8 Z9 d+ o& c
  24.   R9 C" P$ h) |( _. d$ u  l, c
  25.     public function __construct($config) {
    ; j7 u( i4 H6 Z0 @- @( y
  26.         $config = array_merge($this->defaultConfig, $config);+ o7 m/ G! f, W% J; i- P' L
  27.         $mongoServer = "mongodb://";
    / V- [/ a' Z. V8 e  ~, z! W4 c
  28.         if ($config['username']) {$ Y1 P8 _6 {6 @, |6 P3 c# I7 x$ B
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';* N, l9 u( E( r/ ^4 O
  30.         }
    2 R' Y1 V7 L+ p$ E6 m* o+ W
  31.         $mongoServer .= $config['hostname'];
    5 v! P+ b: E) P/ Q1 n
  32.         if ($config['port']) {
    ; ^, B. V% j( W
  33.             $mongoServer .= ':' . $config['port'];
    7 `* J5 j+ v8 x' L' n/ V
  34.         }! j& e; }. {2 H2 {9 p0 [
  35.         $mongoServer .= '/' . $config['database'];
    " P: [. Y9 V" }7 l; h

  36. 2 Z3 `4 R# K8 D: S: ?/ X
  37.         $this->mongodb = new Manager($mongoServer);
    " a! _0 y0 \! a* |3 O
  38.         $this->database = $config['database'];
    ) j6 T/ }3 g- s2 Q1 e  Q
  39.         $this->collection = $config['collection'];
    1 z. l3 O1 T) ]; g. F8 ^
  40.         $this->bulk = new BulkWrite();+ e! n" p0 T3 o. S: c3 X- F
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    , e* R; @8 D0 e  d) V" w
  42.     }
    & i8 m* [7 r, x. r# D

  43. , m, F& f/ N4 F9 [+ ?
  44.     public function query($where = [], $option = []) {
    & F. r; o; t# N' K( U
  45.         $query = new Query($where, $option);8 S$ U( [% H9 ^2 Z5 y
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);4 v5 f2 s6 D; g; D; |+ q5 h$ f
  47. 2 y. y! v+ K# O% Z% h( Y1 Z2 N
  48.         return json_encode($result);2 i1 e  Y1 f. R  E8 f5 d$ r% S
  49.     }1 |( j# Q3 I& Y- o! ]& m1 v
  50. ; Z: _+ r4 ^: V
  51.     public function count($where = []) {
    ' G6 h% ~% {6 E- E6 V
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);. ?, C+ i0 k* Y4 V) w0 C2 p
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    9 O) ^0 ]3 K4 A! z
  54.         $res = $result->toArray();
    1 V( P- c0 X5 ?1 y+ h
  55.         $count = 0;
    . b' T9 o, P( m: Q! r
  56.         if ($res) {
    7 G6 Y3 P/ b/ ^5 l. C. {7 ~
  57.             $count = $res[0]->n;+ y$ Q( e/ ?% k
  58.         }
    0 t' G8 L) ~" E7 K. `/ V; |

  59. 1 V" F8 e+ w* x+ Q! i/ V! t! _! S
  60.         return $count;
    # r1 g" ~: R3 q' o2 F; t
  61.     }
    ; f+ O- A  B5 ?& u0 j9 |$ [

  62. % R& V* f! Y8 B
  63.     public function update($where = [], $update = [], $upsert = false) {! _" [9 Z7 c5 N6 Z7 [6 ~+ M# `
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);  E4 J: S7 K9 N* }2 C
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);, A: D) w7 s; B. E5 J
  66. 2 d2 ]& L1 R% i2 m
  67.         return $result->getModifiedCount();  M7 H9 {1 o- E+ k. p: k
  68.     }. o2 F/ R" ?- l9 [! z0 x9 n& A' d

  69. 8 k' L2 e2 t$ g* Y, h4 ^
  70.     public function insert($data = []) {: _* s4 Z9 A: E1 H  N, G+ [
  71.         $this->bulk->insert($data);5 b. `2 N6 a0 ]) {* ^% j! _# D9 G
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);5 P9 {8 I0 g6 C

  73. . o. u; L) G$ q4 W* z; h
  74.         return $result->getInsertedCount();4 U- {4 a3 y* T* o4 o; C
  75.     }
      G% t! Q. I! d5 J0 U* g# n% ?
  76. ) |) a$ Q+ U) p$ ~, k5 C9 o3 ~
  77.     public function delete($where = [], $limit = 1) {9 ~& ?" p( h/ k. {# G4 w  w
  78.         $this->bulk->delete($where, ['limit' => $limit]);5 L+ h# q, X; V/ F0 d
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);6 r( Z! @- N; X" X

  80. / ]5 J& ~% ?* l6 W  ?0 s
  81.         return $result->getDeletedCount();) i* A0 {0 @  u/ J
  82.     }
    ( O1 w$ ?' R$ U0 F1 i# G
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • ! {; `& e* ^: P5 ]/ Z, k" l9 }
  1. new MongoClient();
复制代码
  • ! o# @( H5 m, j% V6 q
  1. new MongoDB\Client();
复制代码
2.新增

  • ! L0 M; z, C: a5 }6 \
  1. $collention->insert($array, $options);
复制代码
  • ) j- P' i3 p; z
  1. $resultOne = $collention->insertOne($array, $options);//单8 X0 {1 Y4 q6 z9 P4 f" B  I
  2. $lastId = $resultOne->getInsertedId();: c# ~7 T7 t  ?" t. S
  3. $resultMany = $collention->insertMany($array, $options);//多3 j' c4 `4 x, s4 E7 H7 b
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • , c' g# c! a# ^! Z& g
  1. $collention->update($condition, [0 C0 q- m! c" ?: P9 r" Q
  2.     '$set' => $values
    - h3 ]& ~. d  g- W
  3. ,[6 N: l7 n# P  c; E
  4.     'multiple' => true//多条,单条false
    8 @" J6 Z7 f. p$ k7 p, G& ]* G. s
  5. ]);
复制代码

  • . p7 Z, V' Y$ o$ R/ K
  1. $collection->updateOne(
      O. f% \. V& |+ b0 ~7 n% h
  2.     ['state' => 'ny'],
    ' ?7 r/ u2 _" o; n0 {# ~( B
  3.     ['$set' => ['country' => 'us']]6 w# R2 c9 c4 s+ K& N/ {: J3 M
  4. );1 v5 C; {5 m) ?8 u( k7 O( y
  5. $updateResult = $collection->updateMany(9 W  ?! |6 W6 |! z3 i
  6.     ['state' => 'ny'],
    $ C% F- q9 J( V: V3 O1 B! J& U  ?
  7.     ['$set' => ['country' => 'us']]# s' @6 F4 U! F. ?2 \  Z* f, T
  8. );
    $ v/ Y0 W2 h, S  {# U
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询
  • 7 W# L5 P5 B# z$ {6 K
  1. $cursor = $collection->find($condition, [
    ( Q8 F4 H# Z$ R) r6 ^
  2.     'name' => true//指定字段' s- e' T& w6 B
  3. ]);
    & ~! n. @6 b4 f
  4. $cursor->skip(5);" O- i, a7 ]& P" [
  5. $cursor->limit(5);% t8 Z1 t3 g$ G' ?
  6. $cursor->sort([! e: r" E* z+ J5 X6 I
  7.     'time' => -12 a: W. a" J7 |9 l0 L
  8. ]);
复制代码

  • ! `$ A  o7 x  o3 O
  1. $cursor = $collection->find($condition, [, D9 O+ q; v# Q0 M7 |4 j' F, A
  2.     'skip' => 5,8 t, f. T. ?; N$ p
  3.     'limit' => 5,5 _  ?" Y7 l% z1 c1 j0 J; q
  4.     'sort' => [
    " ~# d1 ~, `) z/ }
  5.         'time' => -1
    0 k9 b+ h; A2 k) E9 H# _( T
  6.     ],//排序4 E" W1 r$ K% n
  7.     'projection' => [
    8 ?5 _  v; A6 c$ c4 z5 G7 Z* ]
  8.         'name' => 1//指定字段) V% _2 S- @2 A% w3 v" x5 L
  9.     ]
      X" s4 o3 ]5 ?+ `
  10. ]);
复制代码
5.删除
  • ' v3 F& R4 s& f/ g  p+ a, W
  1. $collention->remove($condition, [. K5 v- r+ E2 z/ r( A8 o- s" M
  2.     'justOne' => false//删单条
    - N' f! M. A& ^; Q
  3. ]);
    + e: M) `7 @4 V& ^
  4. $collention->remove([]);//删所有
复制代码
  • ; H( w/ p6 W. w
  1. $result = $collention->deleteOne($condition, $options);
    8 O1 W6 O: N# C! I8 Q& L
  2. $collention->deleteMany($condition, $options);
    ; h% x$ P; y* h

  3. 1 @4 ?- @; ^& j  \. F6 q
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    6 [, i8 L  L5 C3 [- X
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    % x  z7 d% K1 j0 t/ Z8 \( y7 u
  3. ], [/ i4 L1 J" T1 R8 C+ `9 \
  4.     '$inc' => ['id' => 1]//自增
    ) a# _5 Q4 n4 r6 @0 B. T
  5. ], [
    4 F# ~1 l/ ]& q
  6.     '_id' => 0
    $ H* P# o0 _- b, p: U9 P. r9 E5 v- i
  7. ], [
    $ y& {7 L. q$ Q3 |. B+ e  t- k6 s
  8.     'new' => 1//返回修改后的结果,默认是修改前的- F/ K8 V& t# F' V
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([$ j2 Q4 v6 L2 W- z1 }
  2.     '_id' => $tableName
    " r0 w3 j- D% X- Y) n6 Z
  3. ], [
    / z  @5 S0 ^1 D' y% Y
  4.     '$inc' => ['id' => 1]4 w4 ]$ @3 C  A6 b
  5. ], [- G- j2 G% T" U
  6.     'projection' => ['id' => 1],& Y$ N! U% N7 U' o% H, t( ^1 s
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    % d9 @% i6 d* F8 g2 c( y8 {1 a5 u
  8. ]);
复制代码
2 c6 h" H: I$ [8 _
; R" ]0 x9 k; j$ S0 X9 r& M
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 10:48 , Processed in 0.055064 second(s), 19 queries .

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