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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11469|回复: 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 r- f+ W8 `7 ]* C
  2. # J8 q0 G2 N: ]$ P# m* Y
  3. use MongoDB\Driver\Manager;. A% U2 R# L+ \+ }0 P4 r2 ~. |
  4. use MongoDB\Driver\BulkWrite;$ p! i% s! p7 n6 `
  5. use MongoDB\Driver\WriteConcern;
    3 P: i$ z0 |" W3 I/ d4 ~  O
  6. use MongoDB\Driver\Query;3 {! @9 E' _4 N& p( S0 Q$ g+ J
  7. use MongoDB\Driver\Command;
      V) ~( \- h: [6 ^5 I0 y0 w% T3 ~
  8. # K' C$ M* I% J6 I$ Z
  9. class MongoDb {
    1 d' S9 \' r1 s* D! L$ H& [/ V% F
  10. ) z8 y4 p. `6 p
  11.     protected $mongodb;( M4 i* `* e. ]* W- j) r4 Z
  12.     protected $database;/ p5 Z1 U% Q" \
  13.     protected $collection;
    4 i( h: @  p. V6 \* S/ O0 T
  14.     protected $bulk;
    & R. S7 O& e+ |
  15.     protected $writeConcern;
    4 C: n9 `9 Z% s2 I
  16.     protected $defaultConfig
    $ h( _2 Z6 {8 l* b2 R
  17.         = [
    4 s8 O0 }; S1 k
  18.             'hostname' => 'localhost',
      J0 o6 `( V0 b: a
  19.             'port' => '27017',
    $ b% K' s: B3 ^  Q
  20.             'username' => '',
    3 b8 g1 d, n3 t8 e
  21.             'password' => '',
    * ^* D3 q: v6 a  z+ k* z
  22.             'database' => 'test'
    . J. d5 b+ w+ D' F3 w
  23.         ];+ y* g$ v! z, C2 l! ~$ b
  24. 8 Q& R7 \9 K0 G1 v2 L  W0 O# M# s
  25.     public function __construct($config) {* L3 q6 T  s+ c' A: s. |  ~9 m# z
  26.         $config = array_merge($this->defaultConfig, $config);* h+ |0 ~8 H, s" C- a4 w' d% k* i
  27.         $mongoServer = "mongodb://";
    " w2 |1 n. }3 L
  28.         if ($config['username']) {
    / {0 J" p8 }# d" f4 e  z9 Z
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    1 \: N# ~' l# n) m
  30.         }" j! g3 l$ o+ g/ ~
  31.         $mongoServer .= $config['hostname'];
    3 P  l# T" k8 x" R1 @2 ~
  32.         if ($config['port']) {
    * l& x' d! \2 t! h  M- E$ M- L
  33.             $mongoServer .= ':' . $config['port'];
    8 m# ^) e8 i- w
  34.         }
    ( V: i) J( P4 q6 f, V$ w
  35.         $mongoServer .= '/' . $config['database'];
    1 K1 Z, g  S2 X$ B& B( @
  36. ! _* X5 k0 v$ }6 I( X  z
  37.         $this->mongodb = new Manager($mongoServer);
    + t" U' x) y7 }  }1 _/ X2 e- b
  38.         $this->database = $config['database'];7 l; `  ~: \: p! a' N
  39.         $this->collection = $config['collection'];& V" z7 R9 a' {; B: e
  40.         $this->bulk = new BulkWrite();
      U2 `/ B, N: e" c5 D
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    0 w( l, u5 X, i; s7 Q& u: t# c
  42.     }
    2 ~! r& w. T! U* j- P: L: c# W

  43. 7 y1 R& x& Y! |- O+ n) ?: F
  44.     public function query($where = [], $option = []) {+ C7 C6 e; |6 X2 R
  45.         $query = new Query($where, $option);5 l: H0 _. W/ e$ P7 q; r
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);4 ?8 M4 Q% v3 |' J( }

  47. , g' N6 A* r5 E1 W) \9 \. x
  48.         return json_encode($result);* r2 R, M; s8 f0 \
  49.     }
    + \" o1 h% E4 ^6 x4 I4 H/ i

  50. 5 \1 g0 N5 P) L9 B8 i5 l- o( u8 }
  51.     public function count($where = []) {  P( Y8 F1 _4 x: C, n, O  w
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);% c- t+ w% ]* G! o. Z) ^
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    ( e1 N) J; }' a" K1 v* j- y# V* F4 b
  54.         $res = $result->toArray();
    / l. N/ l6 _( `- A
  55.         $count = 0;
    / L# {( d0 F# n: r: G
  56.         if ($res) {
    & W' x9 l; G. |& C7 b
  57.             $count = $res[0]->n;
    3 Z  |7 J( f6 z
  58.         }
    9 p- r: H, g5 m/ e( @6 l& w

  59. 8 l8 U# ^3 H3 K/ \) e
  60.         return $count;
    0 \3 P9 Q3 v& q1 \
  61.     }
    & z. r) v- {6 f

  62. % ]& j" V) S/ }( @& ]
  63.     public function update($where = [], $update = [], $upsert = false) {
    1 j8 `0 J; |4 T3 M9 y9 K1 g- l
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    ; z+ V# J$ g5 ~3 w
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    2 d1 s) u7 A# w; d' N" r3 n; S2 F
  66. 7 P/ D1 |. `  F/ W
  67.         return $result->getModifiedCount();
    & v" j) {4 r! S9 r* A
  68.     }7 M2 m! o8 V6 L

  69. 3 w, U, ~! \/ P1 _+ Z7 _
  70.     public function insert($data = []) {" u- g# ^9 t* C3 L# D
  71.         $this->bulk->insert($data);
    ! r. P) q1 h& K) K3 \8 ]
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);. Q" l" H& {& F# f) i

  73. 7 R$ U5 |* Q; [. O+ _: n- S
  74.         return $result->getInsertedCount();4 y3 j* F/ i; |- O; [% {# P/ d
  75.     }& A* _8 q! `5 h  |, A* n! q/ I

  76. 1 ~, S) N/ i/ T. M9 Y- {8 P
  77.     public function delete($where = [], $limit = 1) {2 H. k: f8 Q3 h4 j) o0 w2 E5 S! R% o
  78.         $this->bulk->delete($where, ['limit' => $limit]);; A3 d% ~4 e4 V" @! F
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ) N2 w8 G& N; l' |* @

  80. 9 k- K7 p0 F1 e0 a
  81.         return $result->getDeletedCount();  K/ j# l, c9 M" e: \8 V
  82.     }
    7 n# i6 L8 x# q2 C7 o7 v
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • ( w$ V4 N5 n- P; S+ W3 E5 J
  1. new MongoClient();
复制代码

  • 3 q4 o2 [  D4 N. }# c
  1. new MongoDB\Client();
复制代码
2.新增
  • ( d5 |; H9 o5 }& x. x
  1. $collention->insert($array, $options);
复制代码

  • ( M& o: z2 y9 @6 G& Z5 Q0 F0 z
  1. $resultOne = $collention->insertOne($array, $options);//单
    5 h  {4 _* y6 t7 H* ^
  2. $lastId = $resultOne->getInsertedId();
    ) F6 P9 t/ W& G2 Q8 U1 k
  3. $resultMany = $collention->insertMany($array, $options);//多
    : J4 g, N; j& L+ D- Y
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • , J$ S- d7 m, v  h( C' Y
  1. $collention->update($condition, [
    : G' r# a3 E4 t5 x9 _2 J" J: S8 H7 z. b% D
  2.     '$set' => $values
    4 i3 h( t; }: R$ D7 B3 O
  3. ,[9 l4 F& j7 r+ k, Y1 D* p0 V
  4.     'multiple' => true//多条,单条false
    5 L) S* z4 s) L4 Q& }- g" F
  5. ]);
复制代码
  • : ]& m4 `: T9 M: r& N
  1. $collection->updateOne(
    8 c! K' K1 i! ~
  2.     ['state' => 'ny'],
    , t, D; k$ B5 ^
  3.     ['$set' => ['country' => 'us']]* k( G/ }9 {- G8 F  w3 L3 U
  4. );
    7 F+ n5 }! S6 d
  5. $updateResult = $collection->updateMany(
    ( y8 x4 Y1 w! J! M4 p' g
  6.     ['state' => 'ny'],, T, A  ~" C+ Q8 X; V* _
  7.     ['$set' => ['country' => 'us']]
    7 E( Q- h. {2 ^- a% r" d
  8. );" g( t. b/ N& ~; L8 a
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 2 F- w4 i; ?6 s5 J( ?. A; T
  1. $cursor = $collection->find($condition, [
    + @& _& S! |8 V5 w' C: t# D
  2.     'name' => true//指定字段1 i8 ^4 d- w7 F& J: ?
  3. ]);7 q# |% i$ G7 ?  H- ~! X
  4. $cursor->skip(5);
    0 P$ S: l) ?: k: a
  5. $cursor->limit(5);
    . ?7 L1 z& h9 y; ?+ j4 ?6 z& z/ a
  6. $cursor->sort([0 `& F* {' i& m; d$ o
  7.     'time' => -1# V1 s) W1 R+ q
  8. ]);
复制代码

  • / [8 M% e) x6 e: V* H+ ^
  1. $cursor = $collection->find($condition, [: m$ |) J( b0 w0 \, F  y: W
  2.     'skip' => 5,
    * D' Q# B+ y9 W+ }* ]# U
  3.     'limit' => 5,
    " k$ E9 n7 U9 v/ A) Q2 o
  4.     'sort' => [# S% J- l4 d! H6 q5 ?, S
  5.         'time' => -1; m' G7 j% t' R: U( e' i- A  v6 l
  6.     ],//排序8 q# k; u& u3 q+ W
  7.     'projection' => [
    , a4 f* r, T( N. A6 Y( H! b
  8.         'name' => 1//指定字段' t. y% a, b% s3 D8 Z
  9.     ]
    2 t8 f$ w+ C1 l7 G+ p: A4 n. G; d
  10. ]);
复制代码
5.删除
  • - V# A3 P: ]! `- Q
  1. $collention->remove($condition, [$ K7 V5 r8 A! i6 E# I( a
  2.     'justOne' => false//删单条
    4 k  P! I# l2 w
  3. ]);
    7 Z, [$ y! [6 |1 j* o
  4. $collention->remove([]);//删所有
复制代码
  • 8 ^6 I8 c. ^. }8 p  {9 }9 K2 p
  1. $result = $collention->deleteOne($condition, $options);! P! z% Z$ i5 ?7 @
  2. $collention->deleteMany($condition, $options);& w/ \4 }$ R; m1 n
  3. * Q, O; Z+ D' m8 O% i1 o
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    / ^9 {# i3 N& {0 M4 _2 ?
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    6 S6 P& P5 a7 V: K1 J& O, Y
  3. ], [( h, W; L( L. Z3 |
  4.     '$inc' => ['id' => 1]//自增% o2 a8 z: y: X
  5. ], [- Q* T( S- U, [( o
  6.     '_id' => 0
    9 N  }5 d+ G2 i/ n9 p  y  }
  7. ], [
    ) |3 U3 `4 e2 D6 L
  8.     'new' => 1//返回修改后的结果,默认是修改前的# Q2 D( e9 |) e% b, _, x
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([9 ^2 z9 c+ Y3 Q2 c0 _
  2.     '_id' => $tableName2 r, o6 q: X, O/ e
  3. ], [! Y' u% I5 T! s; V+ m$ ~2 Y
  4.     '$inc' => ['id' => 1]
    2 ~+ F! g1 d3 F) d7 G4 h) u# w0 t) Y
  5. ], [. j. H4 _$ o1 m  `8 v
  6.     'projection' => ['id' => 1],3 z9 O4 |) n" Q$ z
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER- C& K& d9 v; L& \3 p
  8. ]);
复制代码
$ _# W6 }6 P" X1 a
1 J" R* U  z, O5 j+ i5 `
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-17 16:31 , Processed in 0.139907 second(s), 20 queries .

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