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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11228|回复: 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. <?php5 K  L& t! I: X9 L) T% D

  2. * n- M, V, m# [# `
  3. use MongoDB\Driver\Manager;
    : D! M. U9 R6 {$ z2 A7 N* v
  4. use MongoDB\Driver\BulkWrite;  L  S1 h9 }( ]! g! x
  5. use MongoDB\Driver\WriteConcern;
    3 U* ~$ @# E5 D3 @, y! {( K
  6. use MongoDB\Driver\Query;! E0 v8 c' F8 j8 ^) S: H, E
  7. use MongoDB\Driver\Command;" D- W" N( L& V

  8. 2 N* w* s6 q7 w
  9. class MongoDb {
    + {9 w2 C8 O- [, P2 _
  10. $ ?' Y( }) [5 E: E3 H
  11.     protected $mongodb;
    : ]$ ^% w+ ]! r8 C5 b# n
  12.     protected $database;
    + F3 ~- k' ~8 r2 s: n/ D9 E
  13.     protected $collection;) q' U3 J7 _8 `6 z2 r4 J  h, @- d
  14.     protected $bulk;
    ( K; z' y, Y; e8 y
  15.     protected $writeConcern;) G& T; [' y+ `' G1 m1 K
  16.     protected $defaultConfig
    . |# U0 j. f1 r
  17.         = [
    # u) F/ J( i- y; I" |. V
  18.             'hostname' => 'localhost',
    ! W+ m3 k; ?( b9 W! t7 q
  19.             'port' => '27017',
    % Q$ P. i- k, P* F* X
  20.             'username' => '',3 L& q$ ~; d* W3 |* M! V
  21.             'password' => '',
    7 H4 f& H$ y) K! j& j6 ]! N
  22.             'database' => 'test'. t! Z& @3 ^  E! q; O
  23.         ];0 p, T7 C- W; E9 r+ k
  24. * v  @8 [# w- L- F! M. i
  25.     public function __construct($config) {# Q+ k, G' u* r& K- t
  26.         $config = array_merge($this->defaultConfig, $config);9 I1 p# f$ I# V+ q2 h! X
  27.         $mongoServer = "mongodb://";
    3 {5 z2 z" q: Y  g: X  K0 N/ Y
  28.         if ($config['username']) {
      E9 E0 a, Z7 T' D  v' e; F0 ]
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    + H  @8 S( {( h
  30.         }
    $ y2 f7 I: m  m" h* g
  31.         $mongoServer .= $config['hostname'];
    9 d5 T2 T2 U4 r  E/ f& c6 ]+ H- R
  32.         if ($config['port']) {
    3 M, r) j5 h1 q+ s4 O# j2 Q! W
  33.             $mongoServer .= ':' . $config['port'];
    * b9 O2 B9 A, U  a5 d& V6 o: G$ X
  34.         }
    2 g8 y( u/ s/ `- C
  35.         $mongoServer .= '/' . $config['database'];. K/ r( ~0 U9 C3 I1 ^( {
  36. . ]# F1 \+ G6 c: [9 a
  37.         $this->mongodb = new Manager($mongoServer);
    0 ^% N. c& H2 b' S# {# ^$ ~$ d% D3 ^  A
  38.         $this->database = $config['database'];4 w0 y. ?* t, P
  39.         $this->collection = $config['collection'];
    ( h1 K- n5 H# G" ~" |( E8 k
  40.         $this->bulk = new BulkWrite();4 _* i0 u1 S. z# u% F! q1 Y
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    8 U3 ]: T$ K' x! n
  42.     }8 E. K2 A. i; r8 U+ I

  43. * _: G, j# J5 a' M( t1 Z5 j) H
  44.     public function query($where = [], $option = []) {* u' \% P9 G' X" r& f4 v) f, q
  45.         $query = new Query($where, $option);
    2 G+ _7 t0 L% h$ W9 C/ o& X( p$ J( q
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);1 w- l1 l3 M6 ^* U% }

  47. 7 o8 V" U5 @3 E4 T, k
  48.         return json_encode($result);" K2 g5 f6 L, y0 i& K. C. W
  49.     }" ]' J7 l% U3 h4 y9 `& u2 U

  50. 3 W* M. F/ L. `( m3 S
  51.     public function count($where = []) {
    4 @* L4 D6 ^% z# i# a/ }
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);8 W5 X. b' H3 v' W3 E. m
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    , {: [0 o* F2 T7 |$ M
  54.         $res = $result->toArray();- [6 Y0 w, X7 z. ~" V
  55.         $count = 0;+ s1 X* V2 d& U+ V
  56.         if ($res) {
    * d& f( ]0 I. U
  57.             $count = $res[0]->n;$ e0 x, o6 S( W& k6 G
  58.         }
    6 x: n7 S  s6 M- c

  59. : ]  \; x# r* ]$ k# h4 M
  60.         return $count;8 q# B) H6 C5 S( p! M7 ~' A4 ^
  61.     }2 `- K) e* O  c1 k9 V) A

  62. ; v% f% j* Y- {* x  D7 p
  63.     public function update($where = [], $update = [], $upsert = false) {
    / }, d# e& u: ?6 k( q4 f/ ]
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);5 q0 k  N# f% Z6 ^: N- @/ |
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    . P* \3 }. m/ l3 [. [  m: p
  66. 2 n+ U8 O# {# T% {6 |( D5 ]" e
  67.         return $result->getModifiedCount();( t! G4 q3 f3 x3 M! i& r0 z- z
  68.     }* Z% f; ]2 w3 Q5 y
  69. 4 z/ q2 X4 W4 E1 V8 I( j
  70.     public function insert($data = []) {) }$ {9 M7 B: b- f
  71.         $this->bulk->insert($data);
    & {) Y% X) t6 Q6 M  {  }5 J
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    0 [: A2 |3 k, y/ L0 _+ W. V' I
  73.   q! z4 Y4 `' a& X) l2 H7 o9 V: @
  74.         return $result->getInsertedCount();
    2 y1 _: p7 b8 l3 W* {
  75.     }. u7 x; f. P1 E; W& D  G" T
  76. # |  L. H6 B' g4 g& _
  77.     public function delete($where = [], $limit = 1) {
      P6 A: g5 b& A6 n! j
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    5 L1 V" q$ J& \; E
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);$ h2 t/ {' M1 @: q/ X
  80. ' e( S' r4 P) N& \# p
  81.         return $result->getDeletedCount();
    1 z7 L; Q' W6 o8 J( \, \# I2 U
  82.     }- s. V+ A6 W/ z4 @: r
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • 7 Y; R# V# }0 [3 b- ~. O7 V) Q1 q
  1. new MongoClient();
复制代码

  • + U. ^0 g; d& O7 `
  1. new MongoDB\Client();
复制代码
2.新增

  • ( p# P4 h8 t8 u$ |/ x$ u
  1. $collention->insert($array, $options);
复制代码
  • " J: x& p. k$ }6 o- O# J0 ~% O
  1. $resultOne = $collention->insertOne($array, $options);//单) m% l4 m7 T* T0 |
  2. $lastId = $resultOne->getInsertedId();
    9 u" d  E5 B1 @0 k8 u) P
  3. $resultMany = $collention->insertMany($array, $options);//多
    & b+ @( j6 T/ e8 C
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • $ X& F; J4 i9 j* ?+ I2 M+ {
  1. $collention->update($condition, [
    5 P' s7 Y% N. f- |  r6 |
  2.     '$set' => $values8 w1 }2 ?( s2 R$ U  r% A' _0 F
  3. ,[
    8 S1 m3 a( F" n4 A+ Q6 j: h; O
  4.     'multiple' => true//多条,单条false' T& D1 C1 K/ o" {+ @
  5. ]);
复制代码

  • $ Z: n; D' a* k- _+ Y0 I+ T
  1. $collection->updateOne(6 ^' f7 N# W+ K. A0 t) J
  2.     ['state' => 'ny'],+ v9 d' p1 ^4 S. Z% a
  3.     ['$set' => ['country' => 'us']]
    7 f, b3 ?: e& Q: c  T5 k# l
  4. );: m) m4 S& v, N( e
  5. $updateResult = $collection->updateMany(, I% N2 d, G5 C, x( l
  6.     ['state' => 'ny'],
    % |, y3 q$ m' }" c0 E0 d4 X
  7.     ['$set' => ['country' => 'us']]
    6 [9 u; K* [" a& n; J$ [- b2 }' @8 C* ?
  8. );9 I, o4 F7 t8 w5 U6 B7 r0 ?
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • , D6 |0 |) X( O$ @+ H" w3 _
  1. $cursor = $collection->find($condition, [% y3 q  J) r$ T" A9 U
  2.     'name' => true//指定字段
    0 y( ?; F- a/ @" u6 B; U# D9 o! b( r
  3. ]);
    ( e8 y/ D! k# p( q" y
  4. $cursor->skip(5);/ l" b, P0 s, \
  5. $cursor->limit(5);
    3 V& H- r% ^8 {' B
  6. $cursor->sort([
    5 y$ q4 ]; y4 {7 M5 D
  7.     'time' => -1, |+ M, s1 M  w: [0 z
  8. ]);
复制代码
  • ' M$ k: S) R/ F4 W$ H# l. ?
  1. $cursor = $collection->find($condition, [
    5 c! u: U* j6 s; d
  2.     'skip' => 5,
    4 J( @( q8 }3 B# Y5 X
  3.     'limit' => 5,
    2 c& `& Z# X2 B
  4.     'sort' => [
    - L- r& T9 e1 D4 {
  5.         'time' => -1
    + q* w" a+ u# v/ }, V# e2 l
  6.     ],//排序
    2 k+ T  t. y; f6 r" P
  7.     'projection' => [
    2 Y* U! L/ W  B2 {
  8.         'name' => 1//指定字段
      }: d: l3 w+ c& }+ O( ^3 _; R) F
  9.     ]3 D# D' R8 H1 S* x0 g" E! i
  10. ]);
复制代码
5.删除

  • . h' ]6 P# X4 A; p* Q2 p: O
  1. $collention->remove($condition, [
    1 {& k% U% P$ n8 A
  2.     'justOne' => false//删单条
    5 z$ ]4 }: [8 z
  3. ]);+ c2 B$ s2 j4 F" s( \, h, ~6 t
  4. $collention->remove([]);//删所有
复制代码

  • 1 [% h% @& y- A- z( ?, \
  1. $result = $collention->deleteOne($condition, $options);
    ! U& x  v" ]& P9 Z* p+ k
  2. $collention->deleteMany($condition, $options);
    ' i8 P) k" M  s1 c5 ]
  3. " [% y/ s- Z0 Z5 F, X/ ]! f
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    * B1 Y$ X+ Q) D/ @
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键  z& \8 h7 J( {5 W9 |+ c
  3. ], [
    0 e& F2 Q2 Q; K4 V0 d) f6 N$ y+ O
  4.     '$inc' => ['id' => 1]//自增% R: M6 H4 X% z9 n2 {# j. B
  5. ], [4 `+ R9 N: d) A: a4 u
  6.     '_id' => 0
    " u4 F, b9 r7 T
  7. ], [
    ' @! U' g* Q# l
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    3 e1 Y( O& E. |  o, j; u0 v
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    9 i+ C# H' a3 B" z* R6 F6 m
  2.     '_id' => $tableName
    . V6 k+ D6 k, Y6 s9 k
  3. ], [$ w+ c6 W+ {+ [8 H; B' q
  4.     '$inc' => ['id' => 1]
    4 w( Q3 h' @. H2 U, x
  5. ], [* ?- j& ^7 M7 M1 X: w. r. v/ w
  6.     'projection' => ['id' => 1],1 E) K/ `( E8 {1 B# i  v$ ~+ Z
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    ; l- J: Q0 e2 o/ X8 l# J
  8. ]);
复制代码

7 C% @1 P! ?( h$ x+ {0 w8 e1 H, P$ s
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-3 01:01 , Processed in 0.113912 second(s), 19 queries .

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