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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16541|回复: 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# ?! u4 h$ `1 P2 m8 s/ x9 R2 ]* w6 v
  2. 8 r# ~& m( i+ z& V
  3. use MongoDB\Driver\Manager;
    ) i6 r" N0 @& l5 G* m- f) U
  4. use MongoDB\Driver\BulkWrite;( |! c6 I- S: I9 b& P, u/ I7 w
  5. use MongoDB\Driver\WriteConcern;
    8 Y* ^) R) a$ D! R- t. G
  6. use MongoDB\Driver\Query;1 T+ c+ R! y9 F9 Z
  7. use MongoDB\Driver\Command;
      u+ \. }6 Q+ W8 m: ?7 D) Q4 \

  8. % \" l8 B7 M/ G; m0 S0 C) i
  9. class MongoDb {: l, s9 C2 Y, r. ]  A
  10. ( }/ T* M4 I! ^" s( y' B) E9 O0 ]: A4 @
  11.     protected $mongodb;
    ) D3 F4 R) y- g+ R) O1 y
  12.     protected $database;
    + @- ]; `/ P, [6 J( k
  13.     protected $collection;
    0 g& ~7 l1 Y0 p  F# L
  14.     protected $bulk;
    % l, x& a; N9 v& S4 f
  15.     protected $writeConcern;6 X3 |5 M" F1 W* G2 V
  16.     protected $defaultConfig
    , y* e# Z. O" w: ~; E: }. [
  17.         = [6 }$ h8 g1 x1 I" Q. p
  18.             'hostname' => 'localhost',8 G% W8 D" H/ T; u; B  w
  19.             'port' => '27017',
    3 W" p* N1 e" ~2 I, d
  20.             'username' => '',5 f/ y! g9 U* H7 k8 z0 p$ `
  21.             'password' => '',
    5 _: q& }' g9 |2 a
  22.             'database' => 'test'. B! P/ J/ b2 s
  23.         ];
    0 G0 Q8 |! m6 e$ }$ U. H1 `( ?

  24. " U# x+ {5 d) ^- `
  25.     public function __construct($config) {, O9 n7 r' [, n$ v3 I; W
  26.         $config = array_merge($this->defaultConfig, $config);
    " T0 U# s  T$ c1 J2 k) M* G
  27.         $mongoServer = "mongodb://";0 N/ I  |  ~! B" a. q% S% [1 C1 f
  28.         if ($config['username']) {6 i; Q+ W/ \7 N) B* f4 P6 G
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    6 m/ e& \0 }1 r2 S) l
  30.         }1 L6 O  o( ^0 ^3 W- Y1 c# u
  31.         $mongoServer .= $config['hostname'];
    9 Q" R" B8 `6 k4 S2 b
  32.         if ($config['port']) {8 D$ e% E1 L( f; x. R6 @
  33.             $mongoServer .= ':' . $config['port'];3 I1 R$ S8 U( M& }: R
  34.         }
      C( g4 L+ T; U* L% A: Q4 b
  35.         $mongoServer .= '/' . $config['database'];
    4 q/ q/ Q) u) F' W9 V: a$ T

  36. # F. L0 i8 K9 z
  37.         $this->mongodb = new Manager($mongoServer);
    ! z  N0 M$ Z  d8 z
  38.         $this->database = $config['database'];
    " X9 L  V1 a1 P6 n* J; b0 t
  39.         $this->collection = $config['collection'];
    / r, F+ ?  B' k- h5 @! x0 ?/ i
  40.         $this->bulk = new BulkWrite();
    3 Y8 m& }! W2 w7 a" x
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    - H" W  w: N* d0 i; ^0 r) H* |3 {
  42.     }5 ~" ~* k! N' i) b) T4 L, O
  43. , y: b+ r, j" }  O! a0 U/ u; d
  44.     public function query($where = [], $option = []) {* I. e  f, j/ L& l; [
  45.         $query = new Query($where, $option);
    ! ~+ J% D: q& i4 o8 h
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);! I! ]1 Z3 i4 ?4 o) J

  47. / E/ ~1 M  |: j  y$ g
  48.         return json_encode($result);) N2 v7 |& F) x; r. {1 p
  49.     }+ m' T1 _% j- j% S% Y, H0 m3 a
  50. ( j+ O2 s6 D+ _1 {" n* y2 u# V
  51.     public function count($where = []) {. t% D6 k' D# P3 V. y5 `1 B2 [
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);$ ?: h' m( ~7 z& J4 j7 @( T+ ~# w
  53.         $result = $this->mongodb->executeCommand($this->database, $command);* K7 M0 z2 ^. D  o
  54.         $res = $result->toArray();/ F" g4 k8 M) _
  55.         $count = 0;
      L, T; ^) O) I6 t$ D0 l' W8 Q0 a
  56.         if ($res) {8 D5 ]* N' c3 S) j5 b( w2 ~
  57.             $count = $res[0]->n;7 S4 L) Y+ @3 n* [% `5 R0 B: K
  58.         }! `7 t2 V( c5 a& t) C" Z; s
  59. 0 o7 R0 S6 U, F! e3 r9 ?. }: }
  60.         return $count;
    ' w, }1 k* K+ z% w- p$ M' h
  61.     }; [0 s/ N2 ?  m$ x9 _

  62. ) W6 u+ s9 k, a+ H
  63.     public function update($where = [], $update = [], $upsert = false) {
    - ], s, ~; S  B" Z2 j# {
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);1 z; h" R1 K: \; t7 Z1 k
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    % y3 u% h5 R# m( m

  66. 3 ]; F. W, x* `9 w) H
  67.         return $result->getModifiedCount();! a- D2 v$ v0 V: f! v. i$ A
  68.     }
    * z  g5 W# @5 M" ?9 _5 y- h/ t
  69. 9 Z; @0 X+ I- w9 v( a0 Y5 k
  70.     public function insert($data = []) {
    ! R0 a& c  l6 M! |* G! ?. ~& U
  71.         $this->bulk->insert($data);
    ) H; q1 e/ l. Y3 O' d
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);7 }$ d# @9 I" ^% Z1 \2 K4 _0 e
  73. 0 {9 @- Z5 R* B4 t' s
  74.         return $result->getInsertedCount();3 v* c$ |; a2 D6 h9 G
  75.     }" e% m0 d0 I( r) ?3 V' `- g, `
  76. 2 ]; ~, M+ j* [
  77.     public function delete($where = [], $limit = 1) {
    & n) `* A, D! {, `
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    * n! l# j+ F2 O6 P0 \
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ( i; ^7 C- f/ ]) Z& Z% Q  {
  80. 5 h9 o6 m: R& u% k% s) b* Y! D
  81.         return $result->getDeletedCount();
    7 y4 h8 U/ }1 Q; Z
  82.     }- x& [/ E, {$ V2 [- T' ~
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • 9 i: w( o8 b) G! }; a5 M( O
  1. new MongoClient();
复制代码
  • & ]* B) {8 }( v5 ^5 Y0 V% [7 ]+ S
  1. new MongoDB\Client();
复制代码
2.新增
  • 9 i; z: |6 F- U0 y3 u( }8 [
  1. $collention->insert($array, $options);
复制代码
  • 2 P1 |  p- {, c8 |; {8 M9 X7 f" B
  1. $resultOne = $collention->insertOne($array, $options);//单  |- z# c) D: N5 f; m* b7 t: Z5 H% P
  2. $lastId = $resultOne->getInsertedId();
    % H4 G9 w  R* i2 ~7 c
  3. $resultMany = $collention->insertMany($array, $options);//多" ?  b$ d' @4 O4 P# q/ A
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • # R" S7 I6 e8 A/ Y+ |
  1. $collention->update($condition, [) \/ N( Q, o' b
  2.     '$set' => $values
    3 y% w) H- M$ f) F, @. ?
  3. ,[
    $ V8 R! j6 {7 @$ F3 e1 y" V  p9 Q5 ?
  4.     'multiple' => true//多条,单条false
    & r6 i4 q& ~* l' |1 ^, I3 ?
  5. ]);
复制代码
  • 3 a2 r/ T. F' V
  1. $collection->updateOne(* w# A$ w7 m$ ^" d/ s
  2.     ['state' => 'ny'],
    6 q1 ]/ ~1 j$ w
  3.     ['$set' => ['country' => 'us']]
    ' w5 P$ v5 x2 U2 U5 a
  4. );
    . Q  L6 t6 K7 b6 u( T( p" K. C  r
  5. $updateResult = $collection->updateMany(
    3 y1 n: O+ R7 ?
  6.     ['state' => 'ny'],
    5 S! R3 b! g+ t- o1 g) y! l
  7.     ['$set' => ['country' => 'us']]
    4 v1 e% g8 G* T8 r* U8 }$ s: }( R
  8. );
    1 K7 K- T4 B  C3 f& V; M( R
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • / J. S( R3 V( }! \; L# L
  1. $cursor = $collection->find($condition, [
    - g! W1 P( x. s5 O. _9 n
  2.     'name' => true//指定字段
    ' ]) C; ~) S& S3 L2 k
  3. ]);
    7 l2 ]. N1 ^1 V; A9 D) `
  4. $cursor->skip(5);' y; m3 b+ ^9 ]/ |% e
  5. $cursor->limit(5);
    5 |' q& G5 V3 O! n6 D. s
  6. $cursor->sort([
    ) b! |5 @$ l. O4 {
  7.     'time' => -1
    * u5 f- q, F, B& {# Y
  8. ]);
复制代码

  • / w6 _8 N; k$ Q! f
  1. $cursor = $collection->find($condition, [
    0 o! k" o2 Y5 a3 e! I0 N& N5 g
  2.     'skip' => 5,4 o) S% x0 }; U" ~  d% q$ \* o
  3.     'limit' => 5,5 N( Q& d3 r4 D4 S! r
  4.     'sort' => [6 }/ Q2 v6 L. P: l# {
  5.         'time' => -1
    . ~' L$ X9 F" u( ^5 Y; @
  6.     ],//排序3 b3 i8 l! T- A6 s' }! d8 q
  7.     'projection' => [
    1 y+ }* ?. F) r' e/ |4 e. D. f8 E( s# ^* v
  8.         'name' => 1//指定字段6 P5 t+ R  Y- s4 G9 U' h; ]8 Z
  9.     ]
    / Y( t9 l$ i* Q% y9 o
  10. ]);
复制代码
5.删除

  • 6 t2 \% m& y6 j) n. D. H
  1. $collention->remove($condition, [
    2 P( m0 {2 r' l' B- h* `2 _
  2.     'justOne' => false//删单条
    ' {, D! T( }9 w( |9 I
  3. ]);$ ?$ ^2 }) p; y/ y3 d+ [0 e* V" l
  4. $collention->remove([]);//删所有
复制代码

  • 1 j6 e" t7 h- ~6 q
  1. $result = $collention->deleteOne($condition, $options);
    8 R  g% M7 B- i: A$ |6 [# z. E
  2. $collention->deleteMany($condition, $options);
    ' g4 f$ ]$ Z+ c- O& M3 Y; r5 J

  3. , H& Y. p9 k# |& v6 B% e3 e8 W/ D
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
      p  G/ `: |. ]7 c9 U% p" A9 @
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键! z5 r1 D9 h/ X/ F+ N7 ^, H
  3. ], [4 Q7 T: `7 I- T$ D- o# _
  4.     '$inc' => ['id' => 1]//自增" R! I+ ^( I8 A) \. I
  5. ], [  t# [% u  d: l2 U+ |/ M& _: k
  6.     '_id' => 0- l  r" \! ^  G8 b
  7. ], [
    & u( D( W/ n* Q( a8 E0 a1 ^
  8.     'new' => 1//返回修改后的结果,默认是修改前的$ u3 U! d0 g2 g# W0 h" Y
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([8 G8 z+ N& I- G) |7 I
  2.     '_id' => $tableName
    2 a2 U2 D$ R9 P* L! L( a
  3. ], [0 _6 J8 k% Q3 m+ ]5 X: g; h1 e4 o
  4.     '$inc' => ['id' => 1]
    & v6 A  t  {' U: Q0 ]. r9 V$ P6 Y
  5. ], [
    . ~  d5 p  [7 P- R! {
  6.     'projection' => ['id' => 1],
    * c- b2 _' k$ f4 c/ C6 `
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER- P5 s+ `+ t/ D1 F0 _
  8. ]);
复制代码

  s2 y' D  W# E6 G- y! i3 z" \- C9 f4 R5 O
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-19 22:41 , Processed in 0.056589 second(s), 19 queries .

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