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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 17013|回复: 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
    & c) ]" x2 I$ i4 e

  2. 5 C. Q/ }- p+ a) \/ I' [
  3. use MongoDB\Driver\Manager;
    * B* O" K8 z& U1 j
  4. use MongoDB\Driver\BulkWrite;
    ; R( O( w4 e* S
  5. use MongoDB\Driver\WriteConcern;
    : N+ _* l$ m* Q+ R, |3 ]( P
  6. use MongoDB\Driver\Query;* h' y# {/ D3 K0 z6 S
  7. use MongoDB\Driver\Command;+ F. Q3 o  e! a' y6 }

  8. 4 c6 H8 b# y: t. W; g
  9. class MongoDb {
    " r$ n* F$ C5 c1 ?' \% H
  10. 1 j' K% K, S. S9 a4 ~( y
  11.     protected $mongodb;
    , }% ?% P9 H5 [1 p. V$ ?2 T2 ]
  12.     protected $database;
      }7 Z  Y$ ]6 c3 y3 h
  13.     protected $collection;
    : o6 [# T/ h& n9 s
  14.     protected $bulk;) M5 _. @+ \. E4 S
  15.     protected $writeConcern;3 e0 Q- c; c+ U3 x1 |" l
  16.     protected $defaultConfig
    4 G) H/ Y" Q8 n' G6 \$ C
  17.         = [' d1 S) r/ Q/ E% G3 r4 ^1 j! K4 A" ~
  18.             'hostname' => 'localhost',8 z5 O* S: t* }  A; W& F0 d. {' K
  19.             'port' => '27017',
    - ~- \$ C7 s$ {! _
  20.             'username' => '',
    6 A4 u3 u+ J! [. }4 r; O
  21.             'password' => '',
    9 ~: B/ Z( R: f* K
  22.             'database' => 'test'
    / D* h( f2 n6 F- m6 i+ u$ x0 n
  23.         ];
    0 n# A2 o! R$ {$ {% d2 ^3 f
  24. ( B, c) d( J- U2 w+ G$ }% D7 @
  25.     public function __construct($config) {. R6 G. ~3 ]% F
  26.         $config = array_merge($this->defaultConfig, $config);
    , X/ w, ^1 }0 P& V
  27.         $mongoServer = "mongodb://";
    7 I; u" N! p0 c
  28.         if ($config['username']) {
    / W1 T" C/ `7 i- {' e
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    8 ]" o1 e, _; L* P5 d
  30.         }: X% T/ _2 Q& A7 z
  31.         $mongoServer .= $config['hostname'];
    9 P  A$ n$ P& c% O' \
  32.         if ($config['port']) {2 G( o. r% d, d3 X* }
  33.             $mongoServer .= ':' . $config['port'];
    1 x1 S3 E: B" S- }  R4 Q' H: s
  34.         }
    3 P; K! _/ x- _& N
  35.         $mongoServer .= '/' . $config['database'];
    8 f$ N5 l3 `# {

  36. 4 T7 p4 ^+ r* B! [7 S
  37.         $this->mongodb = new Manager($mongoServer);1 l* l, U" T. `9 y
  38.         $this->database = $config['database'];; o. o% y5 P# Q) E
  39.         $this->collection = $config['collection'];" Q5 r0 y5 Z. n6 ^& @. N" U& i
  40.         $this->bulk = new BulkWrite();
    ; ^  \9 v% b: @' I( E
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    / V6 ~# O4 Y" `8 n, k
  42.     }
    : Q) }0 Q" O8 W2 c* G

  43. * E, H* }1 }# T# o# f9 u7 c% S
  44.     public function query($where = [], $option = []) {
    # k' z! C$ L* G9 `9 x% i
  45.         $query = new Query($where, $option);
    ) i/ H$ F1 ?" @2 h' T
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);" w0 u+ b. G" K- L7 [

  47. " i! O% ?: `9 n$ V9 V
  48.         return json_encode($result);
    ; w: R  [( }+ ^( m
  49.     }! O! E" U+ ~* i0 W, z
  50. / n8 c: p& v1 e5 [+ ?  g% C
  51.     public function count($where = []) {) }2 _5 Z' B* F& Y( o$ ?
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
      U" C( A) r" M! A' b. r
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
      h% L7 e* ^5 a
  54.         $res = $result->toArray();
    . P3 g6 m$ z3 E( E6 \  M
  55.         $count = 0;
    - o+ l. M' Z* _. k
  56.         if ($res) {
    * G) q; P3 W9 L: c
  57.             $count = $res[0]->n;* }' A# m# m( ]
  58.         }! V6 `4 \' H$ V1 Y) `. f" G
  59. 5 o. N: m1 B% f
  60.         return $count;
    ( u9 p, Q8 K$ \3 R2 Q( W( H! s8 k
  61.     }% R9 \5 p+ {2 _7 u, l3 Y3 k

  62. 6 f4 O! N3 H2 E5 \" Q1 M
  63.     public function update($where = [], $update = [], $upsert = false) {/ I: R4 T3 _7 p. N
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    * s  s* s, @4 R* |: g# M# @
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);# @+ J* G( R5 y% h  a/ a5 J
  66. $ X, m! o. v. W# s
  67.         return $result->getModifiedCount();5 ~3 X* o* @7 W# k7 a/ n
  68.     }9 t) K" m+ b. }+ y

  69. - q+ P" Z: h8 O+ E4 r7 Z& V3 ~, r" M
  70.     public function insert($data = []) {) Z. O# K- N2 ~; L, `7 {  T
  71.         $this->bulk->insert($data);, _0 i7 {& ]' f* w# L' h% w
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);+ y9 U* A  F$ l& O: Q) N

  73. # k: \( F% n7 r0 C/ E0 a/ O" p1 D: p) {
  74.         return $result->getInsertedCount();
    8 O4 h2 v9 `6 o( [# O
  75.     }& ], ~! L0 `0 d. P, [7 D" H2 e

  76. ; J1 \. @* b" v2 q2 \" g
  77.     public function delete($where = [], $limit = 1) {9 w4 m1 S7 R0 l8 n' a& I
  78.         $this->bulk->delete($where, ['limit' => $limit]);* V2 V& W6 |3 M- Q7 E
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    . P1 q/ \8 ^' z! u* c, R1 G9 @/ n# c

  80. " Y7 N" S5 `1 ^5 e6 w5 c
  81.         return $result->getDeletedCount();
    6 Q/ N3 C7 V0 q" E8 `
  82.     }
    " j% |' u; G+ Z( H
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • " z, j  I. t7 B, m4 R1 z
  1. new MongoClient();
复制代码

  • , P5 F* [* l" U) a) G$ ]! p
  1. new MongoDB\Client();
复制代码
2.新增
  • 9 Z, s% j9 Y; t7 M- w
  1. $collention->insert($array, $options);
复制代码

  • ( i9 o- e6 S1 C$ p, J" T) @
  1. $resultOne = $collention->insertOne($array, $options);//单
    , A  O3 A3 T* u9 a6 r0 W2 W4 \1 g
  2. $lastId = $resultOne->getInsertedId();
    9 U9 e. Q; u8 r$ [4 u) l9 F
  3. $resultMany = $collention->insertMany($array, $options);//多
    & w* K; _7 R0 Q" l1 Y
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • 7 Y/ J1 C6 a  i2 g
  1. $collention->update($condition, [5 N" d) p) T! e/ O" y
  2.     '$set' => $values
    ; V2 G; \8 O& F  c% Z$ o  y& o
  3. ,[8 e; C# V9 s! n/ h: l
  4.     'multiple' => true//多条,单条false
    & q# I" ~) m7 `) ^% ?2 }
  5. ]);
复制代码

  • " y; t: ~$ X9 M
  1. $collection->updateOne(
    0 G' ?2 H. x2 Y$ X
  2.     ['state' => 'ny'],8 `  @6 b: K9 c  \' P4 V
  3.     ['$set' => ['country' => 'us']]& F2 T4 T4 S6 ^* i
  4. );6 E6 B/ _* A2 O/ K  `  q5 x
  5. $updateResult = $collection->updateMany(0 ^0 R& G" @" @. o* M
  6.     ['state' => 'ny'],% F( ?( f8 K" p: ^" R( x' Q5 d
  7.     ['$set' => ['country' => 'us']]) z# d% z; C. x7 c6 L8 E
  8. );( r5 d0 D* ]+ U5 z0 K. d% n4 W5 O0 {
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • " s4 T; l+ a( z! d
  1. $cursor = $collection->find($condition, [( i+ S6 m$ y* z; R
  2.     'name' => true//指定字段
    . U+ z5 b- \7 ?& S+ l8 j
  3. ]);
    1 U1 I: Z+ ^  }0 D" e, t7 j
  4. $cursor->skip(5);3 w* B2 A" \) Q* T. @0 J9 E% r- D
  5. $cursor->limit(5);! i/ a. U" m3 f9 t  N7 U. c; s
  6. $cursor->sort([
    5 x: M, _2 n7 i
  7.     'time' => -1. m4 a% b5 I# j% J$ r1 {( R
  8. ]);
复制代码
  •   @' O& h! N4 u- {& G
  1. $cursor = $collection->find($condition, [, d$ p) g( I$ v5 ^' n1 ~1 N
  2.     'skip' => 5,
    ; @2 q  r, d4 y* s1 l  S
  3.     'limit' => 5," a, l5 g5 J+ S9 j+ z' D
  4.     'sort' => [2 A  ?' I1 t) Z( }
  5.         'time' => -12 T$ K% k3 r2 S* q: l
  6.     ],//排序. m9 b. x7 I; }( Y. U9 v* W
  7.     'projection' => [0 w* F3 N  y7 G5 \
  8.         'name' => 1//指定字段; n  ^  v: }% E5 L0 \; A
  9.     ]+ k! c& H  P, w9 p3 g
  10. ]);
复制代码
5.删除
  • 4 F* ]4 }4 `& i" Z- [" I& W: b0 q0 I; Y
  1. $collention->remove($condition, [
    $ @9 X* d4 x1 v( @% ^0 E# O$ R( a
  2.     'justOne' => false//删单条* g! j; l6 {) }3 O! O0 a
  3. ]);
    $ Q  {2 ^* w1 B, \. U
  4. $collention->remove([]);//删所有
复制代码

  • - }9 y6 L. J; Y+ c
  1. $result = $collention->deleteOne($condition, $options);
    , v* B( \1 Q& ~. F/ q' q
  2. $collention->deleteMany($condition, $options);
    ) H. ^% C1 `  D: Z1 U( P) p, u- |* J

  3. 4 x+ z& R# x1 e- j4 k' J8 J
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    ! _4 z+ Q1 \/ c- c
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    3 w8 r1 R; A, a2 L
  3. ], [- j2 F0 t7 w6 \' e" j, l9 O
  4.     '$inc' => ['id' => 1]//自增
    " }) D+ r* q5 }4 b% Q  w. h8 u
  5. ], [
    2 t9 L5 k/ H& {6 p: q
  6.     '_id' => 0
    $ `- D; W( \$ }- E8 i' U7 D9 B$ k
  7. ], [
    8 F) F6 S+ e4 e+ s" V
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    3 b) o8 W7 Y) h9 Z% i
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([* [0 m% `2 T/ ]. Y' [# C  ^9 f
  2.     '_id' => $tableName
    , {) [4 H, R- u
  3. ], [
    ; a9 Y  n/ W3 c4 d
  4.     '$inc' => ['id' => 1]
    # q6 }" j7 f0 ^
  5. ], [/ Z1 \7 b& Q- q$ T; U2 s$ J/ u6 k
  6.     'projection' => ['id' => 1],
    5 G# R* Y- o# i
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER' |" ]' S2 G8 D& S/ \
  8. ]);
复制代码
; O0 ~$ D. ?. B1 v9 |& U

4 S( D8 K5 Y$ r
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 14:18 , Processed in 0.068909 second(s), 20 queries .

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