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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16555|回复: 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
    : k+ f( }0 b! Q# L* |! L" [
  2. , o" M4 T6 O# H& \  R
  3. use MongoDB\Driver\Manager;/ L& s8 f* L# M: O- {
  4. use MongoDB\Driver\BulkWrite;
    " L5 M3 v7 Y5 P# Z0 Q
  5. use MongoDB\Driver\WriteConcern;4 {( f' X: `* _
  6. use MongoDB\Driver\Query;1 k5 l6 d5 d7 e( S( F
  7. use MongoDB\Driver\Command;8 B: w' _$ L. W: _
  8. ; @( s$ g3 t. x) U+ l' R% `
  9. class MongoDb {
    $ m6 g, c, S: U2 w
  10. $ y3 n4 j5 G; J3 P9 U
  11.     protected $mongodb;
    9 _! }, |; m, c9 X( N
  12.     protected $database;* `# S0 A: r0 D& Q! x1 Y
  13.     protected $collection;
    . r' t- g5 [) [* n2 y
  14.     protected $bulk;
    + e& U/ ?4 I! E* _2 _
  15.     protected $writeConcern;( a7 ?8 J7 H0 F2 P) j: T# y
  16.     protected $defaultConfig
    7 N6 [$ l; J5 l5 Q9 G
  17.         = [' ?, d# _; k  h2 l: H( `8 t: ]+ n
  18.             'hostname' => 'localhost',
    / F& U' d. r4 Z7 d
  19.             'port' => '27017',
    ; m6 t0 f" M8 J
  20.             'username' => '',+ V8 F7 G' }% O. Q
  21.             'password' => '',
    3 W6 E: O+ v  b' |6 {1 j/ F
  22.             'database' => 'test'; Z) F: A2 {! Q$ J4 b" q6 A
  23.         ];( I# G% u2 d0 H) Q
  24. 0 v5 N/ D0 s& j
  25.     public function __construct($config) {
    ; H4 ~0 F+ ^7 I' ?0 J! e
  26.         $config = array_merge($this->defaultConfig, $config);
    : C9 q' F. v' k$ H
  27.         $mongoServer = "mongodb://";
    ! S3 M  u5 N% z8 v9 M% E9 z5 r
  28.         if ($config['username']) {0 T0 ~3 c$ o* \# f6 X
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';) W, F, [! J0 u' l) `/ }
  30.         }- {1 d  Z2 f" {/ p
  31.         $mongoServer .= $config['hostname'];* g) K- j( S: a$ O
  32.         if ($config['port']) {
    3 ^  v; G. O* t8 o$ ^: [, \' K
  33.             $mongoServer .= ':' . $config['port'];
    : F5 _1 u- T5 A2 A# ~/ |* f. Y
  34.         }5 G2 T4 H. _5 H* S* D
  35.         $mongoServer .= '/' . $config['database'];
    9 y6 P0 h7 u' I5 F

  36. : x% Y; |7 F6 B2 a& [. G& ?
  37.         $this->mongodb = new Manager($mongoServer);* K' U% C8 L$ J; x) L
  38.         $this->database = $config['database'];
    5 \) P1 `* T5 Q- x
  39.         $this->collection = $config['collection'];, o, L  D  y2 ]' s
  40.         $this->bulk = new BulkWrite();
    9 {; T& G5 E1 n. f! w
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    ) ^$ z' r5 o, }7 u; a
  42.     }
    ) l) D! B5 X+ j3 I1 J, w  V
  43. , ?) c6 }! z8 W$ }1 R
  44.     public function query($where = [], $option = []) {
    7 `+ d- Y4 E% u2 S' j! ]* n, C/ z
  45.         $query = new Query($where, $option);2 D& d9 r/ o8 E- g; x
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);% C0 X1 G& {& x2 Y, T% z8 M

  47. ; Y0 e  l5 G7 ?2 \3 ~5 |
  48.         return json_encode($result);
    1 a% Z+ V$ Y' j6 W  a9 B
  49.     }
    0 W9 ?$ Z! U- t- B! \
  50. " s3 g  H" B6 o# d
  51.     public function count($where = []) {
    4 \  b: a% S, @& x$ ]" G: D
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);0 i- B* J- ]! i4 v0 D" ]" E, z3 j; p
  53.         $result = $this->mongodb->executeCommand($this->database, $command);, N; C+ F. B# n4 q1 s
  54.         $res = $result->toArray();
    # [% b% ^5 o; H$ W& l2 H+ s# f
  55.         $count = 0;
      }9 B! Z  }5 q* V
  56.         if ($res) {' J: G& I* `) Z% D, b) J& \
  57.             $count = $res[0]->n;
    + @4 y* |7 K# O& P+ @- _8 B$ A4 s1 J
  58.         }
    : R0 J: Y& `6 C% w, h* z) L
  59. 6 y% D3 O9 q# \: F# ^9 T
  60.         return $count;, M5 l& e* [1 i- q
  61.     }
    9 ~5 E+ y! G) Z% _1 O% ]  ~' j

  62. ) {" o6 w2 n5 ]6 g; I
  63.     public function update($where = [], $update = [], $upsert = false) {7 m+ x3 n! p* |  f
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);4 P3 d/ a7 T+ C- I4 P
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ( i- s+ Q- U1 B) ]+ m* \4 c
  66. ( R$ z  ?3 d  \/ r9 z
  67.         return $result->getModifiedCount();
    " F, o1 q( `7 M. F8 w9 t, c$ x
  68.     }4 J& p. l/ n% {5 h- G! n
  69. % z5 g' L6 q% o9 `: R
  70.     public function insert($data = []) {/ y2 d0 T+ e. A  H4 E
  71.         $this->bulk->insert($data);
    5 L# V7 Y" V# s. B1 p' s
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);7 r' m% T! _% U$ C

  73. / K* @+ Q* p' `
  74.         return $result->getInsertedCount();
    - S) D% N3 a) v" o/ |: }$ s
  75.     }
    ) y: l/ \9 l' A4 J5 R) o" g' q7 R
  76. . o* l; i2 w' [/ T  X" f( B/ J
  77.     public function delete($where = [], $limit = 1) {! z! g8 [: |. O" e
  78.         $this->bulk->delete($where, ['limit' => $limit]);: Z4 \% h7 ]) }6 C
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);  ^$ k, q8 s, U" M
  80. % G6 q7 D# T4 [4 f/ t
  81.         return $result->getDeletedCount();; b# |% C# E) I9 F
  82.     }
    ; o$ M9 o4 ]5 a# T
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • 8 q0 b6 b' m# O1 {, |' y; Q
  1. new MongoClient();
复制代码
  • . `, v8 v9 l% E( M
  1. new MongoDB\Client();
复制代码
2.新增
  • ' H- @& h6 V- p- t6 [6 q3 Z
  1. $collention->insert($array, $options);
复制代码
  • 7 c# g, c# \: }& e  t$ q
  1. $resultOne = $collention->insertOne($array, $options);//单
    2 E$ n) `8 t$ O, u4 o: Z
  2. $lastId = $resultOne->getInsertedId();
    + e- y( b2 Q' O" k! S
  3. $resultMany = $collention->insertMany($array, $options);//多- e1 u: F& x8 s" f0 ]" Y
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • ) t- N9 H2 K! ~6 m3 _
  1. $collention->update($condition, [
    - q( x. ^, _4 N
  2.     '$set' => $values) G  H& P3 p/ u; M
  3. ,[
    1 X: D3 }9 g6 y, g
  4.     'multiple' => true//多条,单条false2 a/ i$ r5 W/ ]2 D% ~
  5. ]);
复制代码
  • * S! m1 R; s- {
  1. $collection->updateOne(
    3 F1 K+ d6 w6 y8 J1 C" X
  2.     ['state' => 'ny'],
    * Z2 r6 F5 N+ a+ T
  3.     ['$set' => ['country' => 'us']]" V9 a6 W  _) x  Q
  4. );) m1 [- D% e$ U" {* h& g
  5. $updateResult = $collection->updateMany(
    0 p5 T: a* y$ B! h
  6.     ['state' => 'ny'],: y1 K, R1 p/ v: G
  7.     ['$set' => ['country' => 'us']]$ v% j: U/ n! d& x
  8. );
    ; P8 \$ \' D0 m' \  I) S( b# Z
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 4 u! _' N' A- F. }3 _/ ?4 |3 `
  1. $cursor = $collection->find($condition, [
    & [% I: X# M7 S$ [
  2.     'name' => true//指定字段
    ! @6 `; u2 `" U7 o
  3. ]);( `% ]1 W- L0 j. L& p2 |" D1 T! h
  4. $cursor->skip(5);8 a; C- U2 k) g3 \+ `
  5. $cursor->limit(5);0 A; i- R* Z0 i" G0 K
  6. $cursor->sort([
    ' T% W9 t& B" q* v7 \/ p
  7.     'time' => -18 G; V3 G& e% d9 v$ R
  8. ]);
复制代码

  • 3 k8 y" Q4 c2 [: D
  1. $cursor = $collection->find($condition, [7 y- s* F. f, M5 f2 {! M& p
  2.     'skip' => 5,3 V" h6 v# c8 R0 W0 z
  3.     'limit' => 5,
    ' e% D: J' W$ A% {; G
  4.     'sort' => [
    $ J8 A+ i, T2 V9 q6 J2 h' k
  5.         'time' => -1
    - t& t/ D- j8 ~% J2 D
  6.     ],//排序
    ( J* s0 I( f% X
  7.     'projection' => [
      M/ l" J8 |# ?; V2 a4 c
  8.         'name' => 1//指定字段
    : o% ]  I/ b& v9 D$ H* v  c
  9.     ]
    ! s: R& {  L5 |5 n& \. k% G
  10. ]);
复制代码
5.删除
  • # K9 ]& l6 o( H  d6 _
  1. $collention->remove($condition, [
    / V" J6 H5 K) ]3 D
  2.     'justOne' => false//删单条/ S, N7 ^. T7 _5 O+ s" u  h
  3. ]);
    + k, D% ]4 F% P% a) l) \
  4. $collention->remove([]);//删所有
复制代码

  • 3 U1 f" O4 }7 N( P! N
  1. $result = $collention->deleteOne($condition, $options);
    / }0 Y- ~9 [2 m4 d4 Z: R
  2. $collention->deleteMany($condition, $options);, ?/ W: B" g1 B4 q- u9 `8 [

  3. " i" q5 `, z1 C* ?
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([: V/ q! d4 P; e4 [
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    $ `* e& K" u7 N6 K# l' f
  3. ], [$ T- F. W6 d$ {( b) n
  4.     '$inc' => ['id' => 1]//自增0 P2 C* _8 h% B
  5. ], [
    : g9 A9 c5 L+ S" h
  6.     '_id' => 0
    ' C' {8 V6 E' L( \# f
  7. ], [! p& l2 J% ]% ^; S
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    / L5 A5 v; b% k- V
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([- P  ^2 k$ L) ]+ O3 L9 k, J
  2.     '_id' => $tableName
    4 M; d9 p  v$ I; Y% P" e
  3. ], [# r) G. E8 v4 A6 T; E2 g3 h
  4.     '$inc' => ['id' => 1]
    # D! c9 w0 e4 L( k; P
  5. ], [
    ) c3 `4 U  W) Y, {  f2 M; b, W3 I, }# b
  6.     'projection' => ['id' => 1],
    2 O( b- F+ w4 |
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER( w; @" B. L6 v. R+ B( I3 g
  8. ]);
复制代码

/ v$ n8 d4 ^: X( `1 X* `$ d' Q
9 R' F0 s/ m# x, x- d9 E
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-20 05:38 , Processed in 0.060942 second(s), 19 queries .

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