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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 17001|回复: 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. <?php7 X6 ?8 o' G; \$ x/ l* x
  2. ; K  |/ b8 Z) Y+ O4 L+ u
  3. use MongoDB\Driver\Manager;4 T3 N" X, i+ e$ v! b- R6 s
  4. use MongoDB\Driver\BulkWrite;
    * `  J9 A" |6 Q: B) s# V; p
  5. use MongoDB\Driver\WriteConcern;
    1 A& ^9 V. L' t' U$ E, |& q2 }) M
  6. use MongoDB\Driver\Query;
      d/ g9 T+ T; q& k4 t" o3 U& c. Z1 Y
  7. use MongoDB\Driver\Command;
    3 M' [: s1 L( W

  8. ) c& _: F4 q1 ^1 E$ Z' V0 @+ i
  9. class MongoDb {% s% _4 w$ \/ F7 C# X/ Y5 _' y- G. w
  10. . x$ S, I3 `: ]3 a) c( L7 Y7 N
  11.     protected $mongodb;
    % [6 Z. h+ i, I0 T0 y! J
  12.     protected $database;
    5 U6 A. U: X4 f- y
  13.     protected $collection;4 ]$ M8 h  Q. X+ I( J! N
  14.     protected $bulk;1 m; T' b8 b4 h% s( Q
  15.     protected $writeConcern;3 w& Y. n$ w3 u' \) _
  16.     protected $defaultConfig- S9 X7 d8 Y. e: \8 M* N
  17.         = [4 s  J" m, a% A/ v: B
  18.             'hostname' => 'localhost',
    - s4 c7 b# x  h& W
  19.             'port' => '27017',# g. r2 `. ]: o( ~% A
  20.             'username' => '',
    ; O: i) [9 s. O& {1 ^
  21.             'password' => '',6 l) P1 z) b( c+ b7 `  B: ~+ g
  22.             'database' => 'test': \$ G0 z% x* O. L% B
  23.         ];
    9 C* m0 H9 v  @, K

  24. 7 ]3 S/ S( g! J! Q* @6 z
  25.     public function __construct($config) {
    6 C! A; R- x1 |6 r8 C. ~
  26.         $config = array_merge($this->defaultConfig, $config);4 U! _8 W5 T4 q
  27.         $mongoServer = "mongodb://";+ V) C& \0 p. O3 O
  28.         if ($config['username']) {
    $ }0 I1 _+ S3 S; \4 z2 d
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';7 y+ F1 e$ z' Q# V) S# Z
  30.         }' l& V9 A5 ^( y$ r9 g  d0 ]  r$ J$ Y
  31.         $mongoServer .= $config['hostname'];/ {: s0 L1 A' `: _( k7 E4 g* F
  32.         if ($config['port']) {! ?! |6 J6 F& B5 ~+ c- R  I, O- w
  33.             $mongoServer .= ':' . $config['port'];% f5 b  c* ?2 n: w/ y; u2 o9 I
  34.         }
    ( ~: K" P0 }( I2 m2 n; _3 J( ?
  35.         $mongoServer .= '/' . $config['database'];
    0 Z7 J* m' Y4 f" {; Z8 D
  36. 4 _" [1 Q! k- a$ m. ?3 D- y& Z9 E
  37.         $this->mongodb = new Manager($mongoServer);
    4 b/ h8 I( `- y% q4 @7 l! G
  38.         $this->database = $config['database'];
    . ~: z* Q# c4 p
  39.         $this->collection = $config['collection'];
    1 o0 B7 A+ S9 ]: V
  40.         $this->bulk = new BulkWrite();& x6 ]) [3 ~0 D5 B' w" R6 o0 f8 o
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);1 s; L( C  B( K3 k! q
  42.     }
    , z6 {: ]! g$ V, p
  43. , M5 @, d$ |1 Y2 f; p/ B, g1 [
  44.     public function query($where = [], $option = []) {: u0 v5 `! A& S
  45.         $query = new Query($where, $option);6 h" f& P+ W8 W5 P
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);6 H+ E; d6 a4 C- B( G9 h) g$ i
  47. ( M2 f4 k8 G& j) w4 G
  48.         return json_encode($result);
    " z( p6 X- Z8 O' I
  49.     }
    ' R& r+ S+ h! g# l

  50. ! U7 g7 A* g8 ~% l+ _4 r) T
  51.     public function count($where = []) {
    9 v6 r2 G, y9 j( a. g
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    9 p# C7 ]+ k' f" \: R  H
  53.         $result = $this->mongodb->executeCommand($this->database, $command);$ Y; {( y' p; ]# j' r
  54.         $res = $result->toArray();8 G3 y& J5 U3 h8 f
  55.         $count = 0;4 }/ L5 Y1 V" w# }. R
  56.         if ($res) {3 T9 X4 U* g! D
  57.             $count = $res[0]->n;
    $ U7 r2 O! `6 {% n
  58.         }
    9 x8 T+ V, s( \- g+ J

  59. 3 U: j0 X$ W' N
  60.         return $count;" i) [% g# J% ]) l
  61.     }" e# p$ g/ o( b! s1 F2 g0 a

  62. % N5 o) u  ^. E4 z" X
  63.     public function update($where = [], $update = [], $upsert = false) {
    ( v' [# N4 W7 k/ r
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    & m/ S, I- [& T) s8 N6 d# m7 Y5 v
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    7 x* a- }4 S+ N4 X0 W
  66. 5 z% T' u  i$ {0 _; r( V
  67.         return $result->getModifiedCount();
    ! }0 V* \! K  o+ @* p3 O
  68.     }
    & P- v! [7 D, q8 F8 J$ ~) M( W# Q

  69. " _1 `3 P& J: Z5 U* \
  70.     public function insert($data = []) {( `; e/ P* P/ k7 a1 J# z
  71.         $this->bulk->insert($data);
    - s. x9 k) H( N9 M8 U$ `* l( G
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);8 f9 ~# o, T! p! `/ _0 ^& \
  73. + w/ A) W$ x, g5 i
  74.         return $result->getInsertedCount();( ]; ?4 o$ P2 K, _( A0 ?0 T/ ~
  75.     }
    - k1 ]! p2 n2 s! S
  76. 8 O& S3 A; K. J" k
  77.     public function delete($where = [], $limit = 1) {
    # b$ w# T" R* y( B' K
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    # ]! |& E2 c" v, S2 [
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);( g* C+ h5 H3 y9 ], N

  80. " n/ A5 K6 k3 u2 W! \, G4 G
  81.         return $result->getDeletedCount();
    0 i' R8 c8 T( N  g0 B
  82.     }$ S  R$ c6 S& O' I
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • & A/ W+ V+ q& }+ B4 e7 g  I
  1. new MongoClient();
复制代码
  • 9 N- I, i% n* I
  1. new MongoDB\Client();
复制代码
2.新增

  • - @( o0 D) i6 A+ J
  1. $collention->insert($array, $options);
复制代码

  • ! _. v5 g9 }1 d* m% [$ Y4 Q4 z
  1. $resultOne = $collention->insertOne($array, $options);//单! ~! x# F) O5 l6 P- r0 e
  2. $lastId = $resultOne->getInsertedId();9 K" F9 Y, A8 g/ {  H- u
  3. $resultMany = $collention->insertMany($array, $options);//多- G6 L" w* A; D+ F1 Y3 J; p
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • , k0 r. w/ [$ X& l# g. E- f0 m( m
  1. $collention->update($condition, [6 }& o" J$ {; N5 A
  2.     '$set' => $values
    1 |8 Z7 i' w% p
  3. ,[
    ) I% c& ?5 v6 S
  4.     'multiple' => true//多条,单条false1 o) f5 c2 `, z" i! @
  5. ]);
复制代码

  • 1 {- R1 M; D8 R# L
  1. $collection->updateOne(
    : D. J$ C# H3 D# W; z1 B
  2.     ['state' => 'ny'],
    7 r4 s. N1 d& |5 i
  3.     ['$set' => ['country' => 'us']]
    ) X1 W1 ^1 m6 x6 P5 J
  4. );
    & W( I% l$ v& R; w; F0 `3 M! b; `- t
  5. $updateResult = $collection->updateMany(
    - k4 o3 o, D' T+ j1 f- z
  6.     ['state' => 'ny'],
    # C- [9 |3 }0 H8 @  g- W
  7.     ['$set' => ['country' => 'us']]( g' `; |* ]$ J) C/ _+ P6 N% T$ O( @* T
  8. );3 s/ I4 u! m6 r, }) y
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 0 c+ y8 o% M* m
  1. $cursor = $collection->find($condition, [
    ; d" t) Z. c! S1 [# R1 p
  2.     'name' => true//指定字段
    $ }+ L, F% B& k
  3. ]);2 E" m$ q( A$ v0 d' ]( E
  4. $cursor->skip(5);
    * Y4 \7 i* ]2 l0 h7 H- }
  5. $cursor->limit(5);
    2 r% S& ]8 |, F7 F
  6. $cursor->sort([
      V# A0 ^' q0 X& u* }
  7.     'time' => -1- W7 t% }$ p- i. f/ `  {& j
  8. ]);
复制代码

  • 5 v( V1 j# C5 x( h4 v
  1. $cursor = $collection->find($condition, [. \# s/ T1 L* t9 q
  2.     'skip' => 5,
    ; d3 x" X, M" Q  c
  3.     'limit' => 5,
    - `, a1 G( v  r/ B2 \  j
  4.     'sort' => [
    , c+ U( S; O0 k& t+ ?& ^
  5.         'time' => -1
    4 H- Z8 [8 X1 L% `9 A  T; s- t
  6.     ],//排序
    % ]$ O9 m8 C) w* w) ?! J  _& U
  7.     'projection' => [
    9 Y1 C$ S, G0 e; M, `8 J9 C
  8.         'name' => 1//指定字段: L0 n2 v2 Q+ R8 m9 R, D
  9.     ]7 M; s0 i( Z! Z5 m' h
  10. ]);
复制代码
5.删除
  • ; M% L+ f  t1 @: g9 z( l8 i) R
  1. $collention->remove($condition, [6 @& K0 i) u* e$ V) M: l6 c- x
  2.     'justOne' => false//删单条6 j; b7 c, |8 q' m
  3. ]);: K$ Y6 R; g7 _, g/ _# w
  4. $collention->remove([]);//删所有
复制代码
  • # h" p* I7 l/ ~5 ~' `9 m
  1. $result = $collention->deleteOne($condition, $options);* q  P; p+ R9 h1 A
  2. $collention->deleteMany($condition, $options);7 V( Y! h3 Z2 ~5 I# o) x1 ]

  3. + X) L8 M. c' N1 c
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    $ b% S6 p# K/ K$ W& _' {+ k) I
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键8 K" x% M% h. D4 Z# A' K7 M
  3. ], [' G1 D$ [( W; G: z9 t5 v
  4.     '$inc' => ['id' => 1]//自增2 q2 F! J4 k4 r
  5. ], [& z( ?& V2 W+ t, f7 m% {
  6.     '_id' => 0: f8 P. B# W, ]
  7. ], [
    " i. k# f2 l' @: V
  8.     'new' => 1//返回修改后的结果,默认是修改前的6 g5 q1 ]& W1 T1 {0 v8 d
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([# [! h- n4 o+ B; F" ~
  2.     '_id' => $tableName
    ( `& a6 t' h# y
  3. ], [
    " F5 c# {# ~- ?5 v2 h
  4.     '$inc' => ['id' => 1]
    7 R. A0 {/ Z: b# s' T! @  S' k
  5. ], [( ^8 T+ V  a0 G' a5 ~9 x2 X2 W- \: e2 e
  6.     'projection' => ['id' => 1],5 Z1 |; Y( d7 E: g
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    & i! ?/ E& u/ `7 M: K. b, {
  8. ]);
复制代码

& m5 u. A2 L6 w! ?% J3 H0 N# L+ J: R
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 10:51 , Processed in 0.063472 second(s), 20 queries .

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