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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16546|回复: 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
    3 n% g1 o. G. f' G; P1 z8 Y
  2. $ k. u7 k4 b. f( u; Z
  3. use MongoDB\Driver\Manager;
    . b2 x# ^- `: }1 y' b7 l! [! }$ p
  4. use MongoDB\Driver\BulkWrite;$ o% v) G. T; f7 w2 |
  5. use MongoDB\Driver\WriteConcern;: A8 t$ a. Y. ~3 M3 g8 }  j% ^9 P* J9 \
  6. use MongoDB\Driver\Query;
    0 ^3 D, X2 H% c/ ~2 ?
  7. use MongoDB\Driver\Command;! T" E& X) X" X
  8. ! N& O& N' W2 x. p3 ?( i
  9. class MongoDb {
    5 [6 g3 b& F' f' @, `* m5 u' J
  10. $ w3 `+ r' U7 |0 r0 U" G) |
  11.     protected $mongodb;
    9 R3 z$ y2 r# Y
  12.     protected $database;! |3 w& j! X6 l
  13.     protected $collection;
    6 |0 c) H" ?: r- w) U2 |
  14.     protected $bulk;
    2 U* g; S/ H0 X0 H
  15.     protected $writeConcern;+ ^" f& }6 }; {  ?" @
  16.     protected $defaultConfig( R4 A3 r* K5 T
  17.         = [
    / F$ n" e! U, D
  18.             'hostname' => 'localhost',
    ' E) J7 Y2 P. i0 f& c- P
  19.             'port' => '27017',
    - s0 _4 t- B' G
  20.             'username' => '',
    $ ?: @  g8 R5 _8 z9 r9 W! D
  21.             'password' => '',5 M' q0 J4 K; ^) u3 m
  22.             'database' => 'test'6 z. J' v* p- @3 D: t2 u$ m% C
  23.         ];& H$ t% ?6 f. @1 s- ~5 D4 ~
  24. 6 G# \* H: v: B
  25.     public function __construct($config) {7 X; ~# R  z: d" A
  26.         $config = array_merge($this->defaultConfig, $config);
    / L2 X& P1 m$ U% q+ o$ ^
  27.         $mongoServer = "mongodb://";" i/ ~8 L) q% f; J' ~( q( y) q6 ]
  28.         if ($config['username']) {- B& U; }9 J8 }* j) M8 h
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';% ^4 Q# \# O: E" K" \) n: J
  30.         }8 H- _9 ?0 t# u' d
  31.         $mongoServer .= $config['hostname'];$ F4 U- \' o, Y: M
  32.         if ($config['port']) {
    " |; u* O& {3 e! j- A+ }1 |; f
  33.             $mongoServer .= ':' . $config['port'];; K  `8 n0 q+ n+ H+ {
  34.         }, |: D3 N: O# M; k6 n  a
  35.         $mongoServer .= '/' . $config['database'];
    * P% l5 D2 i" t: U" P; H

  36. 0 k9 K& ]- ^, a0 j- L+ B* a
  37.         $this->mongodb = new Manager($mongoServer);7 b% [7 K; L2 E; ]
  38.         $this->database = $config['database'];; s. a& {; j; h. n: y. ?( G; ~2 X( L
  39.         $this->collection = $config['collection'];5 O0 P( U( m) p; ^: C
  40.         $this->bulk = new BulkWrite();
    # k- Q  I8 I" B
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    $ N0 S5 L+ M) R# M
  42.     }
    * E0 n. g: z. N' }
  43. 0 {5 z/ v  q- u( P
  44.     public function query($where = [], $option = []) {0 x9 S3 v( f2 m. b* G
  45.         $query = new Query($where, $option);
    9 y; h1 G7 K& R
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    4 R1 W; B0 D0 X. ]
  47. 0 v) {( t8 R; w/ r: N
  48.         return json_encode($result);7 q' u+ y0 K1 d* L0 y3 k# A( C( w
  49.     }
    - ]# s1 X& V9 c

  50. 3 y$ f- E, o4 [9 B$ k3 Q; h
  51.     public function count($where = []) {1 Y" U9 ]" N4 T. `& G4 C* G
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);6 c  x9 X! H# V
  53.         $result = $this->mongodb->executeCommand($this->database, $command);' l5 w$ |9 F/ S. H! G9 Y
  54.         $res = $result->toArray();
    & q. @! ?: d. @- E5 p5 S
  55.         $count = 0;
    7 `9 Z. c0 x, x; C% I( B
  56.         if ($res) {
    - E5 n8 b6 U8 M( s
  57.             $count = $res[0]->n;9 l% z: D0 y0 a$ ]5 y7 q- Y8 v
  58.         }# v, ]4 ]; ^% V: [6 ~; F
  59. , v% Q4 B/ D4 Y( X8 q
  60.         return $count;
    2 C9 ~; _( E9 I- q
  61.     }5 b3 p8 r. ~6 I6 y% X9 |
  62. ( J& A# O; s+ M! z) i, t
  63.     public function update($where = [], $update = [], $upsert = false) {, v; \" r0 S2 c/ t% l1 R
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    8 p: f) D. F1 W6 w$ y6 t+ m
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    8 @+ z: h" M6 u+ s2 x
  66.   }7 H3 Q0 c7 x/ f  v
  67.         return $result->getModifiedCount();& L5 Y4 @6 q2 b, C
  68.     }* C3 U) T6 Q$ v, N+ ^+ c7 _/ y
  69. 3 \0 F& ^, P8 u
  70.     public function insert($data = []) {* R) h" j3 S7 L
  71.         $this->bulk->insert($data);2 ?0 e" z" R( x& w0 X- F
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);% v* u& w' O# [7 a) i

  73. 3 x- u  X; F* T" D4 n' W
  74.         return $result->getInsertedCount();( O# u9 v) _! k
  75.     }& |' X- F4 W- U: @; Q& I

  76. / h% Y7 X- t% X3 k4 v# _
  77.     public function delete($where = [], $limit = 1) {) |( r% R" r; t. E. @2 j) X6 L
  78.         $this->bulk->delete($where, ['limit' => $limit]);/ n+ c' \% J, k
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);  x2 P1 K1 v" G7 M; i
  80. # y/ h  x) A& A9 |* \/ g
  81.         return $result->getDeletedCount();
    2 F# Y* r% }) ]: J
  82.     }8 I6 V- Z/ M7 A
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • 7 b$ K% f% x6 ~+ g5 c$ C
  1. new MongoClient();
复制代码

  • " c- t8 z2 w, e
  1. new MongoDB\Client();
复制代码
2.新增

  • 7 T# V9 b( F# p1 Z
  1. $collention->insert($array, $options);
复制代码
  • ( W9 k; P; G8 }4 B7 h+ k6 m
  1. $resultOne = $collention->insertOne($array, $options);//单6 C* D" J7 o2 W5 I8 U3 _" `
  2. $lastId = $resultOne->getInsertedId();
    9 P" x3 _* q2 M3 z* N+ S
  3. $resultMany = $collention->insertMany($array, $options);//多
    % H0 b& ~8 t6 Q# C; {6 |
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • ; N" g/ P9 M) ~5 u& |3 m
  1. $collention->update($condition, [
    8 l# T" B0 F9 l  M' T
  2.     '$set' => $values
    " O1 x" z3 N4 R; L+ r. [7 b
  3. ,[
    1 u6 Y, u# f& ?; K
  4.     'multiple' => true//多条,单条false
    5 T) M! @4 _- ?! Q( P
  5. ]);
复制代码
  • - m& I, F% K$ Y3 j
  1. $collection->updateOne(
    / X  z$ P1 p" l, U! n
  2.     ['state' => 'ny'],
    ' ^% e2 J  _- w
  3.     ['$set' => ['country' => 'us']]
    6 J0 L5 K9 @8 u
  4. );9 U( t6 k6 v2 J. N/ W
  5. $updateResult = $collection->updateMany(
    * P3 G% f* k, @7 `
  6.     ['state' => 'ny'],
    " j, Y1 k% b9 n" c' u9 g
  7.     ['$set' => ['country' => 'us']]
    5 j8 P$ [( G) J
  8. );' A: `4 c: {3 F( T1 F' u
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • $ v" @1 O2 l. N% h+ S
  1. $cursor = $collection->find($condition, [! Q7 H/ {+ [# a9 c9 |
  2.     'name' => true//指定字段
    & U. `, Q* C" J
  3. ]);
    & p3 H# r  i$ E$ Y0 N
  4. $cursor->skip(5);
    $ M; F$ F+ h% E% P/ U2 K- h
  5. $cursor->limit(5);# M% {6 D# }  t) ?
  6. $cursor->sort([
    + b1 h; i  m2 v
  7.     'time' => -1' u- c, t9 v9 Q3 W; o. f
  8. ]);
复制代码
  • 2 s9 S, c/ {: |4 u) k. i7 X
  1. $cursor = $collection->find($condition, [
    " |4 f9 h) o8 L! P. x
  2.     'skip' => 5,, g( E: x5 l" U# R  P; ]; K
  3.     'limit' => 5,6 C- P0 }9 L2 }% e
  4.     'sort' => [
    $ a  e- m  d2 }0 T7 W
  5.         'time' => -1
    3 m( y* \" }- C: q8 D
  6.     ],//排序
    3 ?! x  B( n6 }+ q4 y
  7.     'projection' => [9 g! I5 C) q. R- j" ]# X: h
  8.         'name' => 1//指定字段( H, C/ d0 n9 J& _: g
  9.     ]5 N. K) f" ]* @; P
  10. ]);
复制代码
5.删除
  • 8 c% `( u+ N) Q& s1 y! q
  1. $collention->remove($condition, [
    : d: K' D; b. n9 u3 I; [
  2.     'justOne' => false//删单条
    8 w2 c3 L6 ?' n6 r
  3. ]);
    3 a# q3 i7 i: W
  4. $collention->remove([]);//删所有
复制代码

  • 5 Z0 [. S5 \; y
  1. $result = $collention->deleteOne($condition, $options);
    * R/ s6 v( i$ F) O0 M" p" O
  2. $collention->deleteMany($condition, $options);' s  g% {( K+ l+ C, P# H
  3. 5 m& }5 q$ B$ \, K% {" w
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([! p; S7 W  g/ m( `7 `
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    1 k$ n0 q, _3 U+ ]+ k9 S
  3. ], [; T+ ^& p$ X# T8 W# `6 D
  4.     '$inc' => ['id' => 1]//自增& V( Q5 a' o9 W) d7 k
  5. ], [
    0 o& t+ h/ v3 }1 e# X* p, \
  6.     '_id' => 0, ^# C( E5 j5 f9 i7 T, |
  7. ], [+ ^9 i- W% m( v% S
  8.     'new' => 1//返回修改后的结果,默认是修改前的' Y$ m# {" z- s
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([# l& r5 W1 U) k
  2.     '_id' => $tableName
    ; R9 Q  J% O& V1 m' x
  3. ], [
    ( @4 v4 ^, i% U( t. C
  4.     '$inc' => ['id' => 1]5 k3 v2 s" {% \5 W
  5. ], [
    ( J7 d, ?8 {  Q% d
  6.     'projection' => ['id' => 1],/ t, J( K5 x& `! @6 L- M* h
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER7 ^3 w( @# Q. o' s" y
  8. ]);
复制代码
# T6 x) M. W; i9 p  X) f" \

  e9 @" M) C# w
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-20 02:46 , Processed in 0.058070 second(s), 19 queries .

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