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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16361|回复: 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
    " x5 r/ k$ y$ u( N! A" N$ F

  2. " K* N: V: k0 a2 E) A
  3. use MongoDB\Driver\Manager;  Z$ ]( D+ o7 ~; e% L/ u, x9 a" |
  4. use MongoDB\Driver\BulkWrite;; f' `1 d. a" [
  5. use MongoDB\Driver\WriteConcern;
    $ X+ P/ z, z2 r2 n, F- O7 A# }, J
  6. use MongoDB\Driver\Query;
    & [: r: O! G# n* u" d) y: s$ E
  7. use MongoDB\Driver\Command;
    + e9 M- {: K% l$ |/ O

  8. $ M8 K' i; c7 x8 x" t% i; H
  9. class MongoDb {
    4 A% N6 P. C: V$ ^8 M1 D, K) j
  10.   L4 \8 b* M( i
  11.     protected $mongodb;
    ! b3 w+ Y  Q0 U4 ^, x, z
  12.     protected $database;
    ) n4 B, C: y/ b; `0 J( D  v4 `
  13.     protected $collection;
    * G+ Z& G7 ^* \: A$ w
  14.     protected $bulk;
    ( E; i; F' p. a7 E6 _; e7 D2 |
  15.     protected $writeConcern;  a* M+ ]% A) k0 q0 Z+ \+ g
  16.     protected $defaultConfig
    - w4 `9 h/ e# i$ [' Y7 z
  17.         = [6 k2 @: c3 U+ M) B( {$ X! }
  18.             'hostname' => 'localhost',; ~5 b8 q3 @6 y  f6 G  A5 }
  19.             'port' => '27017',6 d. a: n7 L1 h4 f* Q
  20.             'username' => '',6 c' Q0 a4 _2 I4 }: j
  21.             'password' => '',2 ]: H; d1 b. H  C3 ]. C
  22.             'database' => 'test'
      |8 L. i3 N" x1 l3 P
  23.         ];
    ! ]2 E8 B) j4 R, o

  24. ! k3 K1 {+ v3 H) p
  25.     public function __construct($config) {( m/ b7 \3 }3 y: `8 R( b
  26.         $config = array_merge($this->defaultConfig, $config);
    - D, Q; }" K: C9 k0 h4 P
  27.         $mongoServer = "mongodb://";
    7 o7 \  B: D+ y: Z7 a7 R) X
  28.         if ($config['username']) {
    7 {8 Q3 X8 z% V3 w/ h# g( A
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';+ w0 _: X9 a8 Z) b* O& O
  30.         }
    4 w  r2 {( i$ d2 V! }9 j
  31.         $mongoServer .= $config['hostname'];$ h# `5 S2 y: k8 n+ ~' E
  32.         if ($config['port']) {
    0 H0 E0 b; t: B8 [6 H2 U: f
  33.             $mongoServer .= ':' . $config['port'];7 ^1 S( c) r& z$ C! y9 m4 g
  34.         }
    - U3 V" q3 s1 S! }7 \
  35.         $mongoServer .= '/' . $config['database'];
    / @4 r' |2 o2 C7 t# o3 v2 s3 j9 I

  36. $ Z, z3 N( [6 }# F+ Q
  37.         $this->mongodb = new Manager($mongoServer);
      [0 t8 `( s. r" r
  38.         $this->database = $config['database'];3 V6 @! Q3 r  Z0 }" U: u
  39.         $this->collection = $config['collection'];
    # H3 \) R) ?% f- s5 ~9 D! _
  40.         $this->bulk = new BulkWrite();7 W  q$ P6 ^, Q0 A- |
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);% C- i9 t# E' i- m0 l1 q" `# a
  42.     }
    ! z. \6 Z# v& m, m' Z
  43. " c8 g* b6 k8 [
  44.     public function query($where = [], $option = []) {3 k6 g1 C( r: G" {$ }& b
  45.         $query = new Query($where, $option);
    - e7 B5 F: Q9 L' U4 \4 g
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    8 q- p9 A6 i- U# [2 k; E
  47. 0 L2 E; K- @& F1 l
  48.         return json_encode($result);' w' y) [3 Y+ O3 F  V; z
  49.     }
    5 @2 `' J# ]+ p( p
  50.   v  v2 V+ u4 Z$ c6 c
  51.     public function count($where = []) {' a& S  U4 j7 ~: G3 `
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    3 y# W% d5 z7 a  ]. n7 ~4 x( ?
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    ! k1 c& k7 {2 \5 @) B
  54.         $res = $result->toArray();0 U2 m1 J# }) E
  55.         $count = 0;
    . w2 `* J* o; }* I9 e9 j
  56.         if ($res) {6 A3 C9 P  Y; \% {; _5 p
  57.             $count = $res[0]->n;
    & c4 q; k# s/ D& _- D
  58.         }( r) f9 W8 A6 _# N6 ^) K

  59. ! K4 B6 I& ?3 f$ ]( s# f
  60.         return $count;
    2 Z' }+ U4 d" t4 q) f+ |0 p& Y
  61.     }
    6 B" P9 k+ `, H0 R/ S' C: N
  62. 8 Y# `5 p- J! i3 G' X- R
  63.     public function update($where = [], $update = [], $upsert = false) {7 H6 f6 Q/ N  u! q! m. ~
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);9 N7 o' L) y# S6 I$ ]6 \
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);) ^- T. f$ G( \  K+ c

  66. 3 X8 S2 Y' j( U4 D1 |
  67.         return $result->getModifiedCount();
    ; ]: k; d- I7 X7 n0 E
  68.     }) g) }6 p; U  {7 y- q& j

  69. # g; f0 z6 C" `: T
  70.     public function insert($data = []) {, R+ f# R' c# k; S; M' g. e( P# A) ?
  71.         $this->bulk->insert($data);% U) b+ j2 r) [/ _0 W2 i
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    5 ?. R5 K- J5 P/ o  V& G( q% C1 A

  73. ( c0 `' A7 B& {$ B. ]- D
  74.         return $result->getInsertedCount();# Q7 I5 }/ v) I* r% i; a" L4 J
  75.     }, F* ~- P  K/ Y

  76. - O2 J1 ~3 y/ @* n# X* z0 x
  77.     public function delete($where = [], $limit = 1) {4 u* ^8 x4 y4 m8 L
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    " H, S/ L. W+ O# t
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);' k' o- }) h8 y: d5 C

  80. 9 O" d7 P! l- L
  81.         return $result->getDeletedCount();9 j; A8 t7 l/ G+ ~
  82.     }
    : a) ?" H; D, W- {2 a6 G3 ~! O
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • ; U/ f& q, a! q8 W
  1. new MongoClient();
复制代码
  • % I0 f$ _- h' g0 ]8 [3 R3 Z: t
  1. new MongoDB\Client();
复制代码
2.新增

  • & A4 v6 Q, [' `& U5 Y
  1. $collention->insert($array, $options);
复制代码

  • 1 m' {0 D! `, ]/ l/ n/ ?
  1. $resultOne = $collention->insertOne($array, $options);//单
    , l1 p  C! K+ n6 V6 [
  2. $lastId = $resultOne->getInsertedId();
    $ ~  |, C+ T5 G  _8 j6 e1 a$ T- ]3 L
  3. $resultMany = $collention->insertMany($array, $options);//多( {- x+ o7 W. q9 T) C
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • 1 k7 |( S" Z5 ?! P" _/ o
  1. $collention->update($condition, [
    3 E: b& |( |: P' u
  2.     '$set' => $values
    ( a; I! ~  t& d8 i
  3. ,[
    ( b4 I  {  C& p
  4.     'multiple' => true//多条,单条false
    6 c9 E  @2 M6 B% Q/ F; r' n
  5. ]);
复制代码

  • ' P" v; c0 X, B9 Q5 g6 V
  1. $collection->updateOne(
    , x. C0 \1 k1 G: I. o
  2.     ['state' => 'ny'],
    : C6 Y1 r) _. F0 y8 e% r
  3.     ['$set' => ['country' => 'us']]
      k3 O: U4 h0 i
  4. );& E9 ?$ z" k4 }5 s& G- @& T. V! c
  5. $updateResult = $collection->updateMany(  {6 J4 Z* `  M: Q; y5 E5 s" V
  6.     ['state' => 'ny'],; S3 V) v) _$ @
  7.     ['$set' => ['country' => 'us']]
      N( B( B. t+ o0 @& a$ U
  8. );
    6 Y# b/ y, C& d/ t* I3 z
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 7 f% A2 x8 V8 o- n9 W
  1. $cursor = $collection->find($condition, [, Y: K2 V! w  ^# a+ F7 K
  2.     'name' => true//指定字段
    # Y% C8 Y' Z+ u: R5 C
  3. ]);
    1 K( ?- \, w: d, k0 f$ I3 U, i
  4. $cursor->skip(5);# U* X2 C, j4 G
  5. $cursor->limit(5);0 d) Y5 I' Y8 }. A: l6 p7 ?9 q
  6. $cursor->sort([- e& w0 F& h3 l3 [$ g5 Z- e! m1 u
  7.     'time' => -1  a/ N- ?6 g  @, j  i
  8. ]);
复制代码
  • ; [* B. i/ V' S9 J% \" _
  1. $cursor = $collection->find($condition, [+ f* O; v* G3 G( }8 Q
  2.     'skip' => 5,
    - a8 i$ S  {" f4 C1 H+ [
  3.     'limit' => 5,
      ~1 p  L$ c& Z, }  S
  4.     'sort' => [
    " H$ Y+ I) u2 T9 O0 h
  5.         'time' => -1. W! }9 @! l3 M8 _! C
  6.     ],//排序% D3 C" o& X; L2 v* i
  7.     'projection' => [* e0 Y9 C( e9 {& |) |$ e1 p4 M3 Y$ ^
  8.         'name' => 1//指定字段
    4 J, v3 c+ A( J3 N! d; ]
  9.     ]
    3 j; Q# X- j6 L) b% l' q
  10. ]);
复制代码
5.删除
  •   T4 N5 Q7 G  L  A9 y- U
  1. $collention->remove($condition, [; i& Q, v" h3 ?$ V' A
  2.     'justOne' => false//删单条4 B& U, z: S4 o( _
  3. ]);5 @* ?, m% _1 F* Q' E5 M
  4. $collention->remove([]);//删所有
复制代码
  • ) T3 Q0 m% {6 |* a( o. c
  1. $result = $collention->deleteOne($condition, $options);
    , U5 P  j% {/ o+ z+ d; V+ @0 H
  2. $collention->deleteMany($condition, $options);
    6 `) ^5 F( x5 f. ]9 L

  3. 5 a, Q; [+ p4 A+ H  f6 v
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    ! H9 A5 E2 r0 F& M
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    ) {; e6 J3 k6 @" V
  3. ], [6 I9 q5 J/ J3 \% H( ~  M6 l# V
  4.     '$inc' => ['id' => 1]//自增5 }' e& ~- [" }2 G* Y
  5. ], [
    % `# H8 N7 r. S5 K3 p
  6.     '_id' => 0
    1 k9 K: T7 ^% v7 j* F  R" x* N5 Z, D- w, b
  7. ], [- }3 l- A9 q" w3 a- \
  8.     'new' => 1//返回修改后的结果,默认是修改前的9 z5 t( V% L7 I
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    ' U- B8 M1 j5 y
  2.     '_id' => $tableName
    * U3 Q& l" @+ J% j$ f; n" T* @/ G( j
  3. ], [" O6 @( }! e" u- L* ~
  4.     '$inc' => ['id' => 1]
    / T" f2 e$ V% S" d# {  y  k7 ]
  5. ], [! ~7 |7 q4 i5 w$ q9 [* ]
  6.     'projection' => ['id' => 1],* k; m( d7 O# d! V
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER7 Z) b, b7 |, D& z: U
  8. ]);
复制代码
" Z( f. u% R; E1 n
$ W2 t, |4 S0 ]4 W# K
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-4-30 20:52 , Processed in 0.094482 second(s), 20 queries .

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