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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11401|回复: 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
    9 ?; c! N  M8 Z0 }% I* I6 k# a, N* U
  2. # J+ G/ F+ M8 C& n5 N+ l- ~, p
  3. use MongoDB\Driver\Manager;6 {/ `8 o9 i$ ?% |' N
  4. use MongoDB\Driver\BulkWrite;. `! \6 r& b6 b) C' v- n
  5. use MongoDB\Driver\WriteConcern;
    , Y. T) G/ X! B* K( a3 N, h' i6 w# ^3 a
  6. use MongoDB\Driver\Query;
    - A; l2 x! a/ H) K
  7. use MongoDB\Driver\Command;8 C, i2 a+ ~/ U# X) @' ~* i2 [
  8. 4 c: W2 `$ Q* I" f
  9. class MongoDb {, h* O4 [( m/ V- i6 ~) y
  10. 5 [, I/ {& \9 `7 c4 I" i& K  G
  11.     protected $mongodb;2 q0 V5 `! J' h2 `
  12.     protected $database;+ @  @  f" c0 b9 g7 j& z0 d9 v/ n
  13.     protected $collection;
      h+ y) A6 M$ O* [
  14.     protected $bulk;! B0 Z8 d3 z- }* g0 k
  15.     protected $writeConcern;
    % b/ Q# j7 D& U' Y
  16.     protected $defaultConfig
    6 p1 {; m, u0 ^& q4 w0 I
  17.         = [! h& k2 e; Z8 Y
  18.             'hostname' => 'localhost',. C, `2 q/ O; |% }0 S+ g
  19.             'port' => '27017',% T3 q; a! s" n
  20.             'username' => '',% n7 z1 F! i- w2 }5 K2 f
  21.             'password' => '',' H" |! h0 o; J
  22.             'database' => 'test'. Z' M+ W5 F3 p4 k1 k# S
  23.         ];4 E7 t* |# J9 z7 h# e

  24. 6 h9 z( m: f/ U+ n5 U/ q: q
  25.     public function __construct($config) {
    ! I9 T; g! e+ @  t% O
  26.         $config = array_merge($this->defaultConfig, $config);
    ) s/ v7 }( F- r4 E- F2 S
  27.         $mongoServer = "mongodb://";  W( P- {; _2 P* T# c- v1 k- `
  28.         if ($config['username']) {
      V1 n% y5 R$ n/ J9 v3 o
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
    . W& d& q! }! w# p& \2 A
  30.         }# I: i; ~4 r' V8 g' x% m1 f
  31.         $mongoServer .= $config['hostname'];
    : }3 v+ x: h7 W( e$ x0 I6 ~9 e
  32.         if ($config['port']) {/ }" i4 p6 p0 @: R( I& _5 {# p6 r
  33.             $mongoServer .= ':' . $config['port'];
    3 ]3 _7 Q6 R/ L' f( [! O) r3 i
  34.         }
    5 c  I; D. ~, n( G) m. n
  35.         $mongoServer .= '/' . $config['database'];7 ]$ P. n) C% c5 o. r: Q% W
  36. 1 N: y% v& S+ B' c4 o: Y
  37.         $this->mongodb = new Manager($mongoServer);
    * i* @; K; A3 X. Q( n
  38.         $this->database = $config['database'];* _( Y3 x2 `0 @# A; \
  39.         $this->collection = $config['collection'];
    " M" M- A( ?6 ~( d' |
  40.         $this->bulk = new BulkWrite();
    0 M( C; o- [0 |5 k# l: h7 b! g
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    1 E5 t- s0 _3 ^3 L: G
  42.     }, |4 y. ?' i6 f) @# I. I" B4 \
  43. 1 f& s% c( @* s' V
  44.     public function query($where = [], $option = []) {
    8 a. A; {  u* }4 [- {7 w+ y& z
  45.         $query = new Query($where, $option);
    3 K& \2 F; c4 O. e) |( E( |
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    1 O/ D  V* v1 T8 s% }
  47. 6 _6 B6 M/ C! h% d  F( [5 }
  48.         return json_encode($result);
    7 r0 m! `' F- o2 M
  49.     }
    7 ^; |% |4 Y; g( q1 f8 o/ O
  50. % M) x! W3 [  R5 n8 c8 w+ @
  51.     public function count($where = []) {2 {& R& y2 f# P* y
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);3 v8 a# E  C, K$ `9 v' J* L+ ]
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    $ Z/ k, ^& P$ p7 \" z
  54.         $res = $result->toArray();
    , d: c2 W' E* }6 M% Q' i8 j6 f
  55.         $count = 0;, P7 ], w0 i/ E7 U
  56.         if ($res) {  C5 p0 G# l) M+ f7 R! J$ o
  57.             $count = $res[0]->n;
    * }/ F7 {3 g$ u5 h! C4 p0 F
  58.         }6 f+ G, T7 s% t0 a
  59. 1 I  G2 t) ]  {" h3 X
  60.         return $count;
    4 Q; t+ `1 j: ~$ n5 E
  61.     }( _6 d, N3 H& X3 F
  62. / k- N& ]5 X2 J; O
  63.     public function update($where = [], $update = [], $upsert = false) {( B# T# }& [" B  [/ a- c! u
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
    % M* |: \7 {0 V# Q: e- z
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    4 s* l1 F5 ?$ h

  66. 7 F3 J0 z2 s: @( J8 g8 p$ x
  67.         return $result->getModifiedCount();
    ! n( O( s7 F8 I& |4 ^3 Q
  68.     }( {" i0 D+ C' p' i5 R3 }
  69. 0 _& |3 z/ J3 F: Q3 }
  70.     public function insert($data = []) {5 J& {. ~. ?  O6 n6 J& p% U6 T
  71.         $this->bulk->insert($data);
    & u$ M, Y; Y. |4 f4 q% l( G' o
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);. E/ `: z( k: I. R

  73.   E. f! D( ~. |  @4 x
  74.         return $result->getInsertedCount();" W" K: a) d0 d4 }
  75.     }5 }: m) Z# s" ~. ]1 S$ x7 y

  76. 4 c) g' [' N! \6 d+ {1 d, B
  77.     public function delete($where = [], $limit = 1) {
    * L5 E. q9 s/ i! [3 S% E; v
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    5 T5 T& h" ]: E# h9 P3 {, D3 U
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    5 Q; Y! E9 o4 b# H
  80. ; w1 @2 r8 Y9 V3 M. T" v% z
  81.         return $result->getDeletedCount();+ _& T9 l. S" m  x( P" \
  82.     }: p3 T' N$ p! A0 F2 Z2 c* |. v
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • ( X7 k2 k' ~- V+ s3 Q+ L1 H+ r  W9 d
  1. new MongoClient();
复制代码
  • 3 x5 d# C6 l; f! F# ?" K
  1. new MongoDB\Client();
复制代码
2.新增
  • $ ?# q, C2 Z5 s. M. e& L$ m
  1. $collention->insert($array, $options);
复制代码

  • % ~- H$ I/ n- j$ d
  1. $resultOne = $collention->insertOne($array, $options);//单( e6 M% J- `0 s7 n) w
  2. $lastId = $resultOne->getInsertedId();
    + z' @. Y' A( T
  3. $resultMany = $collention->insertMany($array, $options);//多
    . @% _% C' }+ ]# i+ s
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • , t6 y$ I8 ?: _' @" `& M! R
  1. $collention->update($condition, [& ?8 e* M( e8 G* k6 s
  2.     '$set' => $values2 {. H' o. L/ o  s5 d# e
  3. ,[4 [: J# @+ i6 ^$ j3 {# M) r6 L' @
  4.     'multiple' => true//多条,单条false
    5 y! ^& C0 M) B5 p( T
  5. ]);
复制代码

  • ( r2 y& i7 R5 Z: L& d  C, v% P
  1. $collection->updateOne(
    9 ~; g9 w8 G" |% I$ s% K; w. x
  2.     ['state' => 'ny'],; e& ^" @6 u$ E1 c6 Z
  3.     ['$set' => ['country' => 'us']]! I" ^) Y' W3 `
  4. );
    % _& T! L: G! J: m
  5. $updateResult = $collection->updateMany(4 i) j) n( P7 n
  6.     ['state' => 'ny'],
    . m) @1 _- F# k6 _" c! f
  7.     ['$set' => ['country' => 'us']]
      W. ?5 g* x+ B6 I
  8. );
    ! G3 F& {  r' s; p5 M7 N5 W
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询
  • : E# _2 q# l; ?
  1. $cursor = $collection->find($condition, [9 j: D* m. B7 E! K" D5 f
  2.     'name' => true//指定字段
    ( |1 _9 X  ~  O! A& M! \1 R  S
  3. ]);. q( U0 f, B  C, V0 q6 ~
  4. $cursor->skip(5);9 Z2 U/ N) v! r1 [/ \  W1 q# ?
  5. $cursor->limit(5);$ b5 K" e( T9 K; p* C
  6. $cursor->sort([/ Q# x, B6 T2 L- Q
  7.     'time' => -1
    $ q- L" K0 \# Q" H
  8. ]);
复制代码
  • 4 g7 q- H; X  Q  |5 g+ s
  1. $cursor = $collection->find($condition, [
    3 h/ Y0 f# D( x4 O1 ?' F0 {% k
  2.     'skip' => 5,7 c" M7 X. {" H1 }' @* z7 w
  3.     'limit' => 5,
    , n( g1 B! H  Z! V$ Z
  4.     'sort' => [
    " l* d  t' o& ]/ s7 b9 d0 f
  5.         'time' => -1! i# ?  n, g  ~5 i6 ~' ?& ^! v
  6.     ],//排序
    , A: K; E6 |. o7 u
  7.     'projection' => [+ j7 O2 f( I8 u# X1 b
  8.         'name' => 1//指定字段+ T; ?, V' c* ~6 X: T( B
  9.     ]
    ( U; }' f: R: c7 N
  10. ]);
复制代码
5.删除
  • . Q0 E0 `) S- W7 b
  1. $collention->remove($condition, [5 Q4 t& L& y. C. }8 M, Z9 D
  2.     'justOne' => false//删单条
    ! X2 R4 v  W' y
  3. ]);
    4 w. W0 I2 i4 P' q8 \% X2 r
  4. $collention->remove([]);//删所有
复制代码
  • + J0 w* M0 x1 }& t- ^% p
  1. $result = $collention->deleteOne($condition, $options);
    4 i0 J+ E% c! A( N
  2. $collention->deleteMany($condition, $options);
    , ^; ^6 B1 Q# m% @/ k% p; i6 k* j
  3. . Z+ J- U4 x3 L$ l( B" Q0 n2 {3 ]
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    3 S4 r# g) V/ p0 g) h. h9 u
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    ' b  D, M2 t. U' F+ i
  3. ], [
    " Q; n/ g  ]( m
  4.     '$inc' => ['id' => 1]//自增
    " M! @/ P* [! x5 z6 r1 p
  5. ], [
    , V9 O$ l7 y* Z7 M& J0 p* n
  6.     '_id' => 0
    ) x6 t# I9 |: h
  7. ], [
    , `  h- {) L0 Z1 @7 l
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    % U4 d2 a  A. t; t3 E
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([. P% ~0 O$ J+ W( H' E
  2.     '_id' => $tableName3 }0 d8 Y6 x! f% }
  3. ], [5 }) ^9 i; I* A$ A. @
  4.     '$inc' => ['id' => 1]
    % ], T+ L* _: Y) |
  5. ], [. j" k5 g2 }8 {+ I
  6.     'projection' => ['id' => 1],
    9 _% F. ?  D# f6 L" B
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER, r7 i: C3 ?) U; X# s: G4 F$ V" n
  8. ]);
复制代码

: l' W( m0 c7 X7 k
( W6 j" ?- m  T1 `2 n7 R
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-8 10:35 , Processed in 0.148123 second(s), 21 queries .

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