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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16545|回复: 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, M6 D9 c1 Y
  2. . S, N, h$ ]& t6 x8 _
  3. use MongoDB\Driver\Manager;
    - V% ^: `: L- }: }- w. R
  4. use MongoDB\Driver\BulkWrite;
    ' U7 {% s, ~: H$ T5 c
  5. use MongoDB\Driver\WriteConcern;( y) H+ t, ?3 s
  6. use MongoDB\Driver\Query;2 m) v9 |& B$ E' n
  7. use MongoDB\Driver\Command;
    / U  }* c4 p4 c& p( R8 f( K
  8. . C  ?% P2 E0 L/ _' W5 X
  9. class MongoDb {
    5 O, d, k; T5 F2 ]

  10. + H% p; ~0 D' N
  11.     protected $mongodb;
    6 x- m& [4 k: G$ R7 N
  12.     protected $database;
    1 E5 y9 J* s( Q# I
  13.     protected $collection;
    + p. f8 M/ d; O  S) ?
  14.     protected $bulk;7 H( y7 x: `; V; q
  15.     protected $writeConcern;) }' Z5 ]9 d8 N! X
  16.     protected $defaultConfig3 k/ K2 E' |& a1 b& X/ |' I5 }
  17.         = [
    - ^+ n! d; f$ u" Q- j# c" x
  18.             'hostname' => 'localhost',+ R$ w5 G6 Q2 y5 w0 m" W
  19.             'port' => '27017',
    1 D0 J2 f; @4 B3 w. l, b
  20.             'username' => '',
    ( v, a2 \' A2 p5 j# j7 E
  21.             'password' => '',8 f9 G2 L$ }5 q" @5 `$ p( m
  22.             'database' => 'test'
    / k  \+ Q1 W& e4 n8 w% f( q
  23.         ];4 u- i! G  g6 M( o

  24. # Z, z9 d' n6 J8 y: @# w& N
  25.     public function __construct($config) {
    8 t7 Z8 P( P% Z# y) |! t
  26.         $config = array_merge($this->defaultConfig, $config);: M$ V) p: k% F8 N3 ~. \  v3 G# i
  27.         $mongoServer = "mongodb://";
    * I5 a: L# E; L6 l
  28.         if ($config['username']) {
    6 _( \* B$ F; B$ L9 @- b! m
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';$ v2 m+ c7 `( ~$ F" C% o
  30.         }
    , Z+ S' V( @1 }! U/ B
  31.         $mongoServer .= $config['hostname'];, H$ I) q  v; _, Q8 T9 L
  32.         if ($config['port']) {
      a2 L4 ?( o1 h, u* _
  33.             $mongoServer .= ':' . $config['port'];  n# d- \$ [6 G5 ~4 Z
  34.         }, F" J- V% c7 D1 |+ S( G! |
  35.         $mongoServer .= '/' . $config['database'];$ _1 X/ J. |% L) v) T

  36. 6 z+ H4 }# T5 `4 W9 q
  37.         $this->mongodb = new Manager($mongoServer);
    # V8 q3 p: H# y
  38.         $this->database = $config['database'];
    3 W9 T5 \) P' t) U: o
  39.         $this->collection = $config['collection'];
    0 X" ^& X, s& N; {9 D& T# x
  40.         $this->bulk = new BulkWrite();
    " i; A1 C0 @# s3 _- O) `" f
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    ) w4 G! O# @* J" o1 y! t3 G
  42.     }5 M8 v1 z$ h7 p, o; v
  43. ' p  P* `, I1 z! H1 l$ S2 q
  44.     public function query($where = [], $option = []) {
    & u( n+ C# y5 U4 r4 X4 ?; A
  45.         $query = new Query($where, $option);
    8 R" v; I! h& |5 i0 P/ \8 n- x
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    % Z9 o' O: y/ }: P0 o
  47. ( }  k7 {2 J* J
  48.         return json_encode($result);; x" F1 `7 {+ M  j
  49.     }
    4 A" R7 J. ]1 U( L4 |" n) t0 q
  50. ) S& G& w+ ^$ G; j: P7 U( t
  51.     public function count($where = []) {
    ' \! |: W$ T9 N1 m: B: o
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);8 }1 a# T: Y' }+ E  {
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
      D; O/ v+ Y0 a; O  \; J
  54.         $res = $result->toArray();
    4 Z9 v5 P7 }1 G) |
  55.         $count = 0;
    " E+ j" n7 f6 ]* ~  n, r5 S
  56.         if ($res) {
    , y8 E0 P+ W5 C$ Z
  57.             $count = $res[0]->n;" Y) r/ p. c9 y$ o7 k
  58.         }6 }: v; j: W) x4 {) d
  59. ) v! T6 y/ E9 d1 @8 ]5 |7 w
  60.         return $count;
    ) O* U# i. ^7 i9 r4 ]6 Y' P+ U0 D
  61.     }8 P; q/ g) i, ]$ a- p2 O
  62. 4 n6 _! ~. I9 }" @
  63.     public function update($where = [], $update = [], $upsert = false) {
    ( J# n7 _* v1 Q/ T: _: P# Z9 j, s" K. D* O; t
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);% w; q' S6 t- P$ x. D( H3 Y
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    & p8 {( i5 O7 _8 z1 z& i: G
  66. 5 H; N( N8 }0 l, H. I. j1 |% b/ r
  67.         return $result->getModifiedCount();
    ! P2 D) @0 w, a; G* R! o% y
  68.     }
    6 r; w- ?/ f' Z3 e1 h

  69. - ?; ^! K: L3 n
  70.     public function insert($data = []) {
    8 o; r5 s8 V$ P! S" Q' n) X
  71.         $this->bulk->insert($data);
    % O4 P4 B+ n/ X0 q; X: o  d0 i
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);% [; B; V; A( g5 o8 ]* m
  73. . l) A) ~) P1 W: o5 w+ r6 `
  74.         return $result->getInsertedCount();8 e' Z8 ?  V1 `. t' g
  75.     }
    / R$ C3 L/ V& |, A# S$ F
  76. 3 J# j* N' }6 _. o% G8 g- k
  77.     public function delete($where = [], $limit = 1) {  l- C" x/ C3 S( _6 \
  78.         $this->bulk->delete($where, ['limit' => $limit]);4 e) q: f& {  B9 r5 g
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);1 F& ]- J* ?) r5 h5 h/ R" A$ E
  80. 5 Q% T! R$ T$ N" t" g
  81.         return $result->getDeletedCount();. ]$ R- P9 S% i, E# f
  82.     }
    - t0 g; {" e" C& `+ z
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • ' q" @, ^8 F+ S( P7 C
  1. new MongoClient();
复制代码

  • ( ~- w2 y1 ?- D
  1. new MongoDB\Client();
复制代码
2.新增

  • 6 w" o( |% ^4 p6 z! e5 x' l" M. U2 a- t
  1. $collention->insert($array, $options);
复制代码

  • / M3 X1 f+ a4 k, {7 Q5 o
  1. $resultOne = $collention->insertOne($array, $options);//单% ~! Q" `  C) [( m9 J4 K
  2. $lastId = $resultOne->getInsertedId();
    ! f  R5 K9 v; U
  3. $resultMany = $collention->insertMany($array, $options);//多! E3 L3 g9 z, |0 z5 m9 O/ Y
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • 7 ~( t$ ~  x- k, `# u$ o
  1. $collention->update($condition, [
      F' d5 F% I( J, O
  2.     '$set' => $values
    4 l* f" m7 q6 W' C
  3. ,[
    8 y& X4 E' b. ?: g
  4.     'multiple' => true//多条,单条false
    , z* u! ^+ a" B! Z! z7 q( w6 S
  5. ]);
复制代码

  • 3 S2 E" Z# Y# ^* D' [6 H2 J+ n
  1. $collection->updateOne(
    1 r* b4 {) g6 L
  2.     ['state' => 'ny'],! f: Z6 I( V+ t- v$ D) f
  3.     ['$set' => ['country' => 'us']]+ C* W# j% R( t$ \
  4. );, Q" T4 ?2 A2 L
  5. $updateResult = $collection->updateMany(+ \: }( `1 S  \& T; n) O5 s$ Z
  6.     ['state' => 'ny'],
    : C4 a6 K" N6 h& q) H: D+ c! `9 _- e2 r
  7.     ['$set' => ['country' => 'us']]
    : h- k8 p. s3 I+ F$ K0 t
  8. );
    ) O: S! I" t, i8 r( U
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 4 t6 a  i7 H, _1 H5 O1 N
  1. $cursor = $collection->find($condition, [% C6 Z. C' R% I4 n2 o
  2.     'name' => true//指定字段
    , l- g: G; e! y1 R( |
  3. ]);0 I% Z' m* X8 d; Y+ `) r3 E8 S, ~. W
  4. $cursor->skip(5);
    , B) }2 L- ^5 a; ~+ X! W2 N) f% Z
  5. $cursor->limit(5);
    ) W/ V+ \5 R- X! `1 l8 k
  6. $cursor->sort([4 Z6 I3 |% h8 }1 e
  7.     'time' => -1
    # P' |6 K2 W6 s. N
  8. ]);
复制代码
  • / M% t" |9 c" c6 d- ]# i' q# E& ^) g5 |
  1. $cursor = $collection->find($condition, [
    $ j6 o/ P/ l" y6 n4 f9 K# Z
  2.     'skip' => 5,% L+ \; p) g: m" b
  3.     'limit' => 5,5 {0 B+ Z4 ^/ W" L# F2 ~
  4.     'sort' => [
    9 K  @# S2 `' r6 M/ h. E: @* q
  5.         'time' => -1+ L8 y7 {, Q. A
  6.     ],//排序
    2 P. M  Z3 o; ]
  7.     'projection' => [1 n/ H- z& b; {4 L3 l1 f
  8.         'name' => 1//指定字段9 N2 e' H5 T7 W% \
  9.     ]
    * o, r, m9 k8 Y  |. G
  10. ]);
复制代码
5.删除
  • 7 K- p# v$ v3 i, y8 t! O" J
  1. $collention->remove($condition, [
    5 |3 B- l$ [0 A5 X7 g) I
  2.     'justOne' => false//删单条
    / X+ `9 `/ s( _" O; P3 V" Z! D# R
  3. ]);6 p0 y) P4 i0 W  X3 K
  4. $collention->remove([]);//删所有
复制代码

  • , I+ c6 E# s" `9 P" L9 L- D
  1. $result = $collention->deleteOne($condition, $options);* S0 l& g' v  ^* T0 V$ Q: e
  2. $collention->deleteMany($condition, $options);4 ]. T0 I9 G% w8 e7 y% E

  3. % {2 h1 ]  c$ g( z2 k9 h0 ?5 K: W* _/ [
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([& F' s% _6 E$ ?2 ~
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键4 f( f5 X! ~- e! d2 c# f
  3. ], [
    + {4 q3 W4 D& ?0 b
  4.     '$inc' => ['id' => 1]//自增1 Z; l7 I7 P; R$ s
  5. ], [# I6 [6 l0 i0 }& t% \1 I
  6.     '_id' => 03 Y, _6 w8 m) F6 X8 R3 I
  7. ], [* v' N/ Z* N+ U! a; M3 \
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    0 I4 r: L. x. |. u
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([6 \9 E: X" P! |2 \# i
  2.     '_id' => $tableName
    6 |% J. l3 L  _: |" [
  3. ], [
    : _5 K, U4 h. M3 }
  4.     '$inc' => ['id' => 1]
    7 x- z7 N, X2 j8 M* ]
  5. ], [
    ( G! U- M  a* {% Y, q' H8 @
  6.     'projection' => ['id' => 1],* @, E8 m' k# [$ A9 z+ P, F7 j
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER# P' `2 m# B9 ~4 c( ~/ N
  8. ]);
复制代码

8 b" s% h6 y0 a2 p: O  {+ v
% Q& \6 m' x- C( {3 U
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-20 01:53 , Processed in 0.051144 second(s), 20 queries .

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