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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16554|回复: 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. <?php2 t# M7 W' n" q5 I* j) q1 m4 ?, ?5 G

  2. + Z( i/ X6 k- \0 B- `" ^, J$ {
  3. use MongoDB\Driver\Manager;
    ( Z9 H6 `  |" ?; q! n7 F
  4. use MongoDB\Driver\BulkWrite;
    $ n+ r* `0 U2 o
  5. use MongoDB\Driver\WriteConcern;
    & @0 t$ B: d* X) b
  6. use MongoDB\Driver\Query;
    4 w+ @, L. I& z- W" F
  7. use MongoDB\Driver\Command;
    ( S4 q' a0 P; A3 x
  8. 4 O% t+ N6 H5 b8 T
  9. class MongoDb {8 I! B( e  p8 ^' T" H

  10. 8 m& G9 W% P' c$ |$ p- s( m
  11.     protected $mongodb;- x; t5 G4 W0 s! ~4 l) c" T
  12.     protected $database;
    ' k8 N/ I3 V. x+ v
  13.     protected $collection;. g0 l0 N9 i2 l# Y
  14.     protected $bulk;
    ! Y1 Z% `3 b% o1 A' I( Q
  15.     protected $writeConcern;
    1 ?6 }  G* W' B' o7 \
  16.     protected $defaultConfig
    8 Y# j0 J/ e9 C# S
  17.         = [' i7 x* g5 D  L# C
  18.             'hostname' => 'localhost',
    & a1 f& M5 Q+ A+ ]; w
  19.             'port' => '27017',
    + Z6 l0 s2 V/ V4 \+ X) ]
  20.             'username' => '',2 E& Y7 i! L4 ~1 @) G4 L2 o) y. f
  21.             'password' => '',
    # A! |# C$ ?* E1 n7 y3 O
  22.             'database' => 'test'! v2 Z( J8 t' c& ^- _
  23.         ];
    ! M/ b; z: c. \$ p
  24. 3 s+ k% U$ X3 o0 {- M/ J+ D; Q  _4 _
  25.     public function __construct($config) {
    & ~1 L) l/ `# w* p& Y$ ?8 R
  26.         $config = array_merge($this->defaultConfig, $config);
      }% h3 _/ k0 l6 I4 ~' _( z( b
  27.         $mongoServer = "mongodb://";
    7 r9 F" z. p4 s- e1 r" M) C
  28.         if ($config['username']) {+ J( b" y. Z; R, d
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';9 v8 p* R; j. g5 w5 S! J
  30.         }
    0 @7 X8 F9 L. u6 k3 Z8 o
  31.         $mongoServer .= $config['hostname'];" E9 v2 z0 ^- v  D
  32.         if ($config['port']) {
    * ?" T" e3 F4 i
  33.             $mongoServer .= ':' . $config['port'];4 @6 h& s$ q2 u# {9 ~2 i  d
  34.         }
    ( {+ A! |5 Z2 p8 R
  35.         $mongoServer .= '/' . $config['database'];4 r" G& A. W) a, K5 L7 `  V+ |

  36. 3 r( F* ~# M2 b6 F9 a
  37.         $this->mongodb = new Manager($mongoServer);# Q/ q( n8 e5 x! g' g5 V& ?
  38.         $this->database = $config['database'];7 D8 l- ^- G3 s# H# L3 Z3 P
  39.         $this->collection = $config['collection'];' R+ X* N4 l$ \/ U5 w5 g/ x' {% ?( V
  40.         $this->bulk = new BulkWrite();
    7 i2 O3 `/ m9 u" L  d# v
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    8 s( o( \$ s5 n6 h+ Z* g7 A3 P8 ~
  42.     }
      J4 c0 k( U8 @6 t) w% b$ K: A
  43. ' q) i# B3 L# A+ g4 f4 @4 M
  44.     public function query($where = [], $option = []) {2 X  `$ n- N# O7 K9 C
  45.         $query = new Query($where, $option);
    : c% |5 g8 u1 C, Y: @
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);- m/ g" k7 E( X+ d

  47. 1 }6 K0 U# @2 e+ k: @  X
  48.         return json_encode($result);$ h% T9 t; x4 k. j
  49.     }8 ^8 L( Q8 n) \7 l3 D& ]
  50. ( W, L! o  _0 m8 w5 \
  51.     public function count($where = []) {" C* m- ^4 V0 T' U% m! q- y
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    . g. E* }. @( L) g8 i( X
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    ) x! K! Y& x; e1 ]2 B! E, V
  54.         $res = $result->toArray();
    # |+ A0 L) }  g; ]% j. O9 `7 q2 C
  55.         $count = 0;2 T3 G- d4 U& S6 h
  56.         if ($res) {
    ! P0 |; l* }' B% k! O/ c$ O* H
  57.             $count = $res[0]->n;5 B! c9 G+ ]3 o7 d, g) Z, z
  58.         }
    ! F7 @5 f5 q4 ]2 l* L: g9 [6 _

  59. ( L7 b6 o- t/ d
  60.         return $count;
    7 h  N$ _( b/ u0 K+ Y
  61.     }$ w* g$ g" P' B- h
  62. ( s( S1 z8 g6 _: y5 f' {2 _- M
  63.     public function update($where = [], $update = [], $upsert = false) {& R& d1 K% f2 I4 k/ s" ^
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    % F# N* Z: n" s
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    . y" x+ |1 I8 D

  66. , a# G3 l6 P. {! S, ]# w3 z; {
  67.         return $result->getModifiedCount();
    ; a1 `" E; q9 o. j' @
  68.     }
    " ?0 a: R6 W  n# r. P" }! q, r

  69. * e' Y/ x* t5 O8 y/ G) F: B
  70.     public function insert($data = []) {" L! ^# b+ ]* x
  71.         $this->bulk->insert($data);  o6 Y5 n# I+ A/ v) O: [' ]6 l* S3 N
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    2 l* `! ~6 q6 s' _
  73. 0 K% E# @& \; f' K* c* }
  74.         return $result->getInsertedCount();
    + H( [( z  j1 ^6 l" Y: Y: W
  75.     }8 [) ^* G$ z9 G1 a) i+ ~

  76. ! W8 Y4 o6 ]$ \; F
  77.     public function delete($where = [], $limit = 1) {; d. y' Y2 F" ~/ y% d
  78.         $this->bulk->delete($where, ['limit' => $limit]);& f* M+ O$ R0 s! y  P; d. w- W
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);- r4 y% b/ [4 M( m4 V# Q8 q/ {
  80. , m; l8 P, Q/ p$ j: ^, y" B) h$ d
  81.         return $result->getDeletedCount();
    % ?% l' n; a3 O# y& G
  82.     }$ C/ F. K2 b' V$ a
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • * D8 k( w6 B8 t. H7 @) }4 j: z
  1. new MongoClient();
复制代码
  • 8 s- Y  L& ?" h$ O
  1. new MongoDB\Client();
复制代码
2.新增
  • * f+ ?8 q; A) p( E% C* E" q2 V( j
  1. $collention->insert($array, $options);
复制代码

  • ! X& f$ F- L) {# ~1 O9 k
  1. $resultOne = $collention->insertOne($array, $options);//单1 T8 G& J  b3 f
  2. $lastId = $resultOne->getInsertedId();
    , ?) m2 q0 A+ Y+ m& p
  3. $resultMany = $collention->insertMany($array, $options);//多
    8 F2 P& B# J+ P* ?; a
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • & ]" P0 k: T# f8 ~' J% J7 o
  1. $collention->update($condition, [
    & m4 }0 R2 t8 X5 C
  2.     '$set' => $values( m6 |" K& `4 t! j: N- H
  3. ,[
    , ]7 k# j! T( l2 t1 n
  4.     'multiple' => true//多条,单条false! a7 R. |  j) b6 m4 p& Q+ H
  5. ]);
复制代码
  • 1 m* Q$ d3 L) P8 }: e
  1. $collection->updateOne(
    ) L5 j. d+ s4 i7 ]- N9 H' g! n
  2.     ['state' => 'ny'],' c/ U  i7 S/ F' T/ X
  3.     ['$set' => ['country' => 'us']]! ?% D4 w2 r. |3 ^/ M0 F5 |
  4. );1 `) g7 _1 G. _
  5. $updateResult = $collection->updateMany(
    & {9 B# J8 a5 [# M
  6.     ['state' => 'ny'],. a* ^& e4 l' u
  7.     ['$set' => ['country' => 'us']]
    : Y% Q7 ^8 v4 E2 X  {
  8. );
    . I! J0 t# h, Z- J( J+ g
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 8 H1 w2 }! t# P, M) W9 J
  1. $cursor = $collection->find($condition, [
    9 n2 ~, d$ V9 H
  2.     'name' => true//指定字段
    : W" x' d8 U: n3 k: S
  3. ]);
    ; G, d2 ?/ D9 p4 f7 m" ]# g
  4. $cursor->skip(5);
    , @) @  f+ b: V. U# ^* J
  5. $cursor->limit(5);
    7 l3 }1 U6 `% J- u6 Q) H- l" P4 p8 ]
  6. $cursor->sort([% a4 {5 p: A2 n' Z. z" l
  7.     'time' => -1
    3 A8 r! _* F) b3 h$ _& m
  8. ]);
复制代码

  • 7 C# B( K3 V/ p: K0 P
  1. $cursor = $collection->find($condition, [: J- L% v6 |0 W* t3 v6 M
  2.     'skip' => 5,& e0 u3 _% h9 M' `9 @7 N3 a
  3.     'limit' => 5,2 }3 q0 m( S- m: W
  4.     'sort' => [, Y0 N* T/ w) n
  5.         'time' => -1  ]0 [6 p; U% H1 W- S3 q
  6.     ],//排序7 l  u& N3 d  U+ M' @' R0 l$ m* N6 c6 r
  7.     'projection' => [! L1 a8 }3 A; W# I0 V; |4 c# P
  8.         'name' => 1//指定字段
    3 x' D1 E) c% W! O9 {
  9.     ]
    : V% |0 [7 p& [$ N  U! T9 y
  10. ]);
复制代码
5.删除
  • " c' ?( p9 ?/ P( M  d7 `
  1. $collention->remove($condition, [
    - B" ]4 w, V/ J5 Q. v
  2.     'justOne' => false//删单条. W5 J- [8 [; d% B
  3. ]);
    . O+ L" Z. `) S7 q
  4. $collention->remove([]);//删所有
复制代码
  • - U# s. D6 \( a) u$ c
  1. $result = $collention->deleteOne($condition, $options);6 i/ j0 L- |5 C8 C$ c
  2. $collention->deleteMany($condition, $options);
    " o1 z) z% i1 Y# o0 [* O' ~, a
  3. 4 A/ ~; C# k" u$ s5 a( q0 _5 h7 `
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    8 b7 \9 X( g/ Z$ J3 q
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键) M0 [* L/ w/ A, c
  3. ], [9 Z) n7 M, M( s5 F# Y) A
  4.     '$inc' => ['id' => 1]//自增
    : @7 S2 X0 S* g3 }7 p) C' v$ n
  5. ], [( D  m- O- o5 w: ~, O" \/ U
  6.     '_id' => 0
    ( r/ U, A* [* i2 K
  7. ], [
    ' b" z2 @; P, B8 \* y
  8.     'new' => 1//返回修改后的结果,默认是修改前的1 H+ T, q. x; z( s0 W
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([7 N) Z$ b% W( ^
  2.     '_id' => $tableName- u) _* s! a' x4 [
  3. ], [! B- G" b# U$ A2 i
  4.     '$inc' => ['id' => 1]1 u$ \! X/ r  H: P# F. b( i
  5. ], [/ p" w, U9 m" R8 F7 Z+ S! z* E. g
  6.     'projection' => ['id' => 1],0 N4 c8 o! s+ Q+ _0 I: g/ i
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER0 U  ^, x4 Y2 g
  8. ]);
复制代码
( H4 w# X+ L( l( N8 w
' j% ?' d: G+ \* O9 F% Z" a% F
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-20 04:19 , Processed in 0.082269 second(s), 20 queries .

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