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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 12061|回复: 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
    ! Q: `9 |* L! {8 w: x; p* F

  2. . K& d, E; J+ {! e
  3. use MongoDB\Driver\Manager;" u9 O2 ~! I( {7 N* x+ ?# P" Y
  4. use MongoDB\Driver\BulkWrite;
    ) b5 S* Z# s6 g, @
  5. use MongoDB\Driver\WriteConcern;: F- l0 d1 V4 G2 t+ x% r  p
  6. use MongoDB\Driver\Query;4 T' ~/ r$ d1 I0 ~1 e9 [
  7. use MongoDB\Driver\Command;
    1 Z# T1 ^- R/ ]8 A  j* d

  8. 6 B% o/ M+ p9 {; K* N& T+ }$ L1 {
  9. class MongoDb {% z- U6 }6 x- G& G# J
  10. / v+ g' r1 }" U$ ?2 p4 f' H
  11.     protected $mongodb;/ W  Y" R: A7 z  B& y
  12.     protected $database;& {+ F2 H) X0 D; o
  13.     protected $collection;! a. X, [: d. w( `
  14.     protected $bulk;
    4 z% d# k- o/ H& y
  15.     protected $writeConcern;9 E. ]" t( S$ G* Z6 y5 I
  16.     protected $defaultConfig
    3 Q" `# S5 q: I
  17.         = [( J, L( i8 {/ {7 t! W8 f
  18.             'hostname' => 'localhost',
    , t' m9 H/ u7 N7 e$ o1 _& ]; b
  19.             'port' => '27017',0 v/ C6 Z0 D$ R2 N
  20.             'username' => '',
    + n6 b) P' w6 X0 f
  21.             'password' => '',+ l* q/ B+ O. A
  22.             'database' => 'test'
    : N: S/ J, N9 d4 s& E1 @8 E
  23.         ];$ l( t/ P  Q" l8 U3 v8 S1 M. s
  24. + j$ k) i1 F0 U2 ]3 Z8 H; D
  25.     public function __construct($config) {
    / a, w* v# Z! v0 m
  26.         $config = array_merge($this->defaultConfig, $config);
    ! m: C8 o: L, C1 r9 z5 i0 Y
  27.         $mongoServer = "mongodb://";0 @2 |, `  H1 Y6 B2 {+ R/ R
  28.         if ($config['username']) {0 f7 i! t; E+ v( d  H  |
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    . F+ D: O( ]! _! E4 Q( u
  30.         }
    . s4 V+ M' ]" A% z
  31.         $mongoServer .= $config['hostname'];3 P( @2 l" U( q, D0 \
  32.         if ($config['port']) {
    ; @- {$ `- @( j# R  c
  33.             $mongoServer .= ':' . $config['port'];7 j: h7 T) ?6 X, j
  34.         }
    - h4 ]' B# _& U+ c
  35.         $mongoServer .= '/' . $config['database'];* C( Z# E- ?8 ]1 \# ]
  36. * M( u6 B# f8 _2 h
  37.         $this->mongodb = new Manager($mongoServer);
    % c8 i0 K( h7 s2 D, _
  38.         $this->database = $config['database'];  N- W6 r' J9 H) w
  39.         $this->collection = $config['collection'];
    ' A  o* J( W$ \8 E1 c0 K+ J2 m
  40.         $this->bulk = new BulkWrite();; G& K4 M! B" C, g5 x, {2 A
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);* X: R/ |! _$ b
  42.     }
    5 M2 k$ u, w  \* w2 t

  43. 5 Y; f1 Y; [* X6 E2 j6 B
  44.     public function query($where = [], $option = []) {7 D6 z8 W0 _7 h& a
  45.         $query = new Query($where, $option);' n: Y3 @; J; E. v+ b0 I8 U
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);7 G, H$ ]4 p' e, C0 L) G( \
  47. ; U9 @7 q7 Z, k
  48.         return json_encode($result);
    : o( w$ X+ N0 J6 r; i0 i
  49.     }7 a! }! A! Y2 x1 U
  50. + \, X: t- r- w2 n: i; w  A) ~& I
  51.     public function count($where = []) {, ^; J5 Y. v0 I& j
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    1 b- W" [' m) _1 b+ V
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    / z3 f& y3 Z. x; a9 x" g; o9 ?
  54.         $res = $result->toArray();2 Z: O1 R7 j- J6 R9 z* k
  55.         $count = 0;* [" v' ~: z( v( z, w& A& H
  56.         if ($res) {8 l, U4 P3 h- v7 J
  57.             $count = $res[0]->n;# @& @  C3 o# Z  _' P3 m
  58.         }
    + m' }5 F0 b/ p9 B
  59. ' y/ }: s1 V7 C/ l
  60.         return $count;
    3 T* V2 E' l  }! O7 F
  61.     }. R/ g7 n5 Z. s% a+ q. r' S' {+ E

  62. 1 P. O/ F: f8 j/ e
  63.     public function update($where = [], $update = [], $upsert = false) {
    7 o3 y1 b+ |2 \( d& L
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);$ e' y+ I1 ^, p2 a+ Y. E
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ! d: x0 L6 B, s" @+ x# x& i
  66. 6 j' {. }- j% R$ H; ^7 m
  67.         return $result->getModifiedCount();
    2 P. Z- i$ \4 u9 ^
  68.     }
    " ^9 F! C! q! ?3 \8 ?& x# s, ~
  69.   I3 C4 w8 Y' n+ r4 Z( n
  70.     public function insert($data = []) {
    5 Q' g# x/ d$ P0 H1 S
  71.         $this->bulk->insert($data);! Y8 y1 l3 ], F0 C) u
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    + G8 k8 Y! ^3 Y- x
  73. & p- t6 v# Y/ x/ c$ n+ i
  74.         return $result->getInsertedCount();
    # y% X6 T- Z0 {# O' q3 m) ]2 I" Z! k5 j
  75.     }
    : }  ~% m' W- V3 e1 r3 q

  76. 0 M, K/ N  b- B) V
  77.     public function delete($where = [], $limit = 1) {% J, I" D$ z6 Z! D6 x
  78.         $this->bulk->delete($where, ['limit' => $limit]);- J! j, B0 V8 b0 P- e
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);0 u7 V  x0 O% V0 e5 n4 M6 a0 {
  80. 4 d2 t8 u6 t, V( @6 ^; K
  81.         return $result->getDeletedCount();: ]: m  z; E% H' ?+ |' d) g7 m
  82.     }
    6 ~% ~5 }7 d% E# _" z
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • ) |7 X# D9 ^1 ]
  1. new MongoClient();
复制代码

  • 3 D8 Y- h3 H4 C- x; I
  1. new MongoDB\Client();
复制代码
2.新增

  • , z. P$ x* }' V& A6 B9 K7 h" V' m
  1. $collention->insert($array, $options);
复制代码

  • 4 v4 Y# r6 Y) r1 Q; y% Y
  1. $resultOne = $collention->insertOne($array, $options);//单
    ) p+ ]4 O: s' h
  2. $lastId = $resultOne->getInsertedId();
    6 C' F5 E4 \, Z' S( x1 t; y
  3. $resultMany = $collention->insertMany($array, $options);//多) E4 i: Z; `1 g# y4 E, \
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • / P3 G: Z: D9 W/ c
  1. $collention->update($condition, [' U' [; S/ O) y# c9 V5 l3 B8 k2 f
  2.     '$set' => $values
    % c6 {, N6 D! ]' D/ k, A# ^1 o
  3. ,[0 [" g: u, F8 Y& h. e$ j
  4.     'multiple' => true//多条,单条false
    * J, b1 c, H( E' z  _
  5. ]);
复制代码

  • 9 p$ g; H: F& a# D1 `8 A
  1. $collection->updateOne(
    # j: V$ A. m' G" m: H" A' J
  2.     ['state' => 'ny'],
    ! \) @, G- U8 h% A; t) y+ C& ?
  3.     ['$set' => ['country' => 'us']]. d1 I6 M. ^5 j# N& }5 {
  4. );+ y' _. A, t' g0 U" X2 I6 }$ W
  5. $updateResult = $collection->updateMany(
    . m. W% _+ c9 J1 X  ~8 C  l" r
  6.     ['state' => 'ny'],! }) l8 b0 @) f1 p8 [
  7.     ['$set' => ['country' => 'us']]
    ( n$ U6 k( H2 A5 t0 }
  8. );
    6 b2 P5 {3 R1 `$ P+ y- D" q0 e/ P1 e) }
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • / R* A- l( q, t4 O1 j
  1. $cursor = $collection->find($condition, [
    + @! m! U2 \$ G3 n. R
  2.     'name' => true//指定字段1 ~: Q1 V3 n( s
  3. ]);
    8 \  Z; V& ?/ _6 w& A
  4. $cursor->skip(5);
    , U5 _( P  e( A3 D) p9 v, O5 \0 {
  5. $cursor->limit(5);
    , ^8 h# [2 l- ], T5 i
  6. $cursor->sort([
    9 B8 h, n: M( \9 ~6 T
  7.     'time' => -1  k3 t: q, [8 _1 J0 y
  8. ]);
复制代码

  • 1 t; ]" d$ C$ G& j8 N
  1. $cursor = $collection->find($condition, [+ B' P# c! B: ?
  2.     'skip' => 5,* S3 Z+ n. [1 R# i
  3.     'limit' => 5,) V1 q& {% }2 V* ~, r5 k
  4.     'sort' => [4 U  M6 g+ I9 G9 G; h
  5.         'time' => -1
    3 X/ C2 g0 T; j8 ^. [4 v
  6.     ],//排序
    . n$ {# j% H+ W  h5 i
  7.     'projection' => [
    7 M2 n6 G) G  C9 N8 \/ M& {
  8.         'name' => 1//指定字段6 a  {% I  s9 U
  9.     ]
    2 s$ H7 V8 U0 G0 t( _
  10. ]);
复制代码
5.删除

  • ; ]4 X- s7 e2 a3 N3 x8 d! L
  1. $collention->remove($condition, [' a' M. y9 r& O' c7 {
  2.     'justOne' => false//删单条
    6 _$ ~1 S# j7 Z4 A, i! g# D8 x
  3. ]);4 l" A7 X: F8 C/ V
  4. $collention->remove([]);//删所有
复制代码
  • ! m! h: E: g' I! L- x+ }
  1. $result = $collention->deleteOne($condition, $options);  q. w7 s+ a6 z# n" d7 T7 A: X' p, @
  2. $collention->deleteMany($condition, $options);
    7 h8 B7 @/ Q9 }
  3. 1 z$ E5 D2 ^2 u$ a
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    4 O" ]7 [0 B0 F5 f% |* k" u% b; T
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键0 Z/ a1 }  U6 y4 Y
  3. ], [  r; }9 N, ]6 H3 y0 Y
  4.     '$inc' => ['id' => 1]//自增
    7 ^4 I/ {! }/ d% }  G) P/ ?0 \* m0 q
  5. ], [
      C- J5 @+ a1 w# ~2 |7 `0 ~6 p' Y# H
  6.     '_id' => 0, S0 j0 f( F% I
  7. ], [
    8 y2 K1 @, {9 L) q7 \% ?
  8.     'new' => 1//返回修改后的结果,默认是修改前的  N9 @1 c% B" e1 o
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([& W* F" G3 ?/ X/ `8 p$ x5 L
  2.     '_id' => $tableName
    1 x2 S5 O, r0 ~! V
  3. ], [: ]' ?: U, A6 q
  4.     '$inc' => ['id' => 1]2 o2 {8 R5 \/ b1 K: {' a* P
  5. ], [1 _, M) Y3 N( o* y4 `) [" A+ x
  6.     'projection' => ['id' => 1],
    3 c3 i! S+ C% c- ^5 e/ n7 `% Y
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    , o' t4 ?+ Q8 F' K4 L4 c  E' h  ^
  8. ]);
复制代码
* V4 Q+ a2 ^, L0 P1 d+ ~

7 v( T( q5 g1 q
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-6-26 09:59 , Processed in 0.105808 second(s), 21 queries .

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