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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16358|回复: 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
    - \2 J( {8 j  Y; b* o4 ]
  2. - s+ F2 P4 D4 h+ d% k, G' K
  3. use MongoDB\Driver\Manager;' ^- Q- M- A" I7 d: _  Y# g
  4. use MongoDB\Driver\BulkWrite;0 s# K$ x0 N4 S& l" w2 ^
  5. use MongoDB\Driver\WriteConcern;
    3 b! ]* U. f8 V% H& |
  6. use MongoDB\Driver\Query;# d5 k; Z+ l, p, A: X: \
  7. use MongoDB\Driver\Command;1 ^' d  C: K( Q4 k: b
  8. 1 O" X% S5 x' }3 N3 a
  9. class MongoDb {6 K/ y% X1 ^) B7 Z; J

  10. ( Y5 x# p0 c' b* G: z3 e
  11.     protected $mongodb;
    $ l/ D% E, m, [( Y: Q
  12.     protected $database;
    , d1 C, t* @% B. {1 N
  13.     protected $collection;
    " w) X6 j" {! @; v. R& S: {4 |
  14.     protected $bulk;
    & u0 C( k5 ^- E
  15.     protected $writeConcern;. ^0 v* n7 w; M7 N& ^9 c! s' \/ {% h4 S
  16.     protected $defaultConfig
      z( E' B: Q; L
  17.         = [
    0 ~& y! m8 P( P9 }6 m
  18.             'hostname' => 'localhost',
    $ m  S" ~7 ?; _6 q
  19.             'port' => '27017',  V- x# Z/ Q+ L1 Y& P- ?0 }
  20.             'username' => '',1 b" O5 m" O" R( e* I7 _7 P
  21.             'password' => '',1 k+ Q0 F5 T5 v# C! E
  22.             'database' => 'test'
    + c3 h# j* i& }4 k; U' P  |6 w
  23.         ];
    & ^+ g' N9 ?* r# t! k  W: @2 j
  24. 5 X. n! p. w  q$ X$ \, x0 h0 a: C
  25.     public function __construct($config) {/ [& K: B, f% Z# [1 P, Y' }- E
  26.         $config = array_merge($this->defaultConfig, $config);. ?1 y' a) Z* o6 E
  27.         $mongoServer = "mongodb://";
    6 y: p1 L' a* E: c( E. }8 x* t$ d
  28.         if ($config['username']) {
    - R; y3 R$ ^+ S7 s. I- X4 p9 I/ Q
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';9 i6 {; f' X4 G8 y" P4 N
  30.         }
    + W: K2 q6 k+ C2 k0 s* w
  31.         $mongoServer .= $config['hostname'];
    : _  w. Z) ?* m+ x
  32.         if ($config['port']) {
      h/ Z+ t8 ]* N8 R$ j1 U. r, I6 Q
  33.             $mongoServer .= ':' . $config['port'];
    / M( F& i+ E; z6 [6 E
  34.         }
    5 k" c! l1 W4 c+ ]; s0 W
  35.         $mongoServer .= '/' . $config['database'];
    0 `3 K$ A+ Y- [. r8 l$ @

  36. 4 e" l0 L! @  X
  37.         $this->mongodb = new Manager($mongoServer);0 U+ r3 ?/ X" W0 M, G; ^' t0 f7 M
  38.         $this->database = $config['database'];" A5 y6 Q" R6 n' {* X" a7 p
  39.         $this->collection = $config['collection'];# ^; H% I  b$ t. Y' r, @
  40.         $this->bulk = new BulkWrite();
    # m7 u6 B. Q" _* l/ G) v
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    ) E7 |: n. Z- O7 @4 s
  42.     }
    4 ?3 t- f8 Y) j) N1 ^/ c
  43. 0 `. B" _1 D1 U- Y
  44.     public function query($where = [], $option = []) {
    6 ~% M, D: O* \6 q: h
  45.         $query = new Query($where, $option);$ O9 q7 D# D& x4 f. l
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
    4 X, z. h5 O( _- I6 A2 x6 p
  47. 6 X+ |% @4 K* @/ x; F. L& S
  48.         return json_encode($result);
    ; n5 ~* w1 i3 w1 r' L" O% D6 D6 m
  49.     }
    6 I" ?6 W; j. C  Z) D5 z  u
  50. 4 r; M8 m' {% v" O% L2 j
  51.     public function count($where = []) {
    / w0 _# N( ~3 Z- v" p7 o6 \
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    0 {6 X  ?4 O, W
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    9 d% u7 Z+ I* y3 J9 U, Q
  54.         $res = $result->toArray();
    " \: \9 O0 w0 W. [- L
  55.         $count = 0;
    $ @* h3 Q1 j: ^3 t+ d% E( d
  56.         if ($res) {
    0 u2 o% j4 ?7 ?
  57.             $count = $res[0]->n;8 Y' ^. v# M+ V
  58.         }" b9 [' l( p1 }" P" x
  59. 7 W9 Z* ^6 V* @3 O1 z3 _& v
  60.         return $count;
    " A# `. J# o0 }
  61.     }
    $ q! X5 Y: ]3 B" B
  62. 5 j5 {+ q2 C2 P- i, Y% y6 a5 M; a
  63.     public function update($where = [], $update = [], $upsert = false) {* K5 G: A6 }; t
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);+ y7 {% w" R8 V5 d8 m0 W* i
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    4 D% t" w, {! I( S; S% I8 l3 Y- w

  66. ; g/ v, X5 n9 [3 c, T9 u4 A9 O! ]
  67.         return $result->getModifiedCount();: X  @& ?  m2 r* n; I
  68.     }8 m. e1 o$ h; ]5 W/ \1 T
  69. 5 Z( x* V, @1 m, N
  70.     public function insert($data = []) {# S0 H- W7 y% T! Y+ p) L9 y
  71.         $this->bulk->insert($data);
    7 J" ]& b* J5 l1 w' W, k! }( n
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);, r; ~- ]! h4 S, L% J

  73. ' @$ G2 M& Z6 w% r% k" K* j, ?
  74.         return $result->getInsertedCount();
    0 M- I- m6 t! a2 X& A7 D/ W7 j5 Z
  75.     }
    : b" S- G* n) M7 X$ I7 B: E/ T+ d5 W
  76. , n7 G/ x2 B' L: X, N
  77.     public function delete($where = [], $limit = 1) {
    # [8 n& Q/ ]: H+ E" H' g
  78.         $this->bulk->delete($where, ['limit' => $limit]);- G' X% h8 A4 }  u
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
    ; Z2 v6 O& Q1 ]9 ]

  80. 9 o, U# l+ `2 h, O% K
  81.         return $result->getDeletedCount();  p3 R7 j1 f2 n" \) V1 o
  82.     }
    4 }' K: _8 |; @  V0 L1 \  A
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接

  • 8 l) n3 k- m8 d6 @& e
  1. new MongoClient();
复制代码

  • ) v( |8 x8 ?- `
  1. new MongoDB\Client();
复制代码
2.新增
  • 3 S, k7 {5 P0 H
  1. $collention->insert($array, $options);
复制代码
  • - d( U  ^" N0 O
  1. $resultOne = $collention->insertOne($array, $options);//单/ i& D% O7 P3 p2 n0 m2 T; h- }
  2. $lastId = $resultOne->getInsertedId();0 j) b; Y$ O. i, D4 a) R2 y7 _
  3. $resultMany = $collention->insertMany($array, $options);//多% U( d$ r2 B- \4 z) C& l, I2 I
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改

  • # k7 X$ y) ~3 i% `! Y! j
  1. $collention->update($condition, [! i# k* @! m4 A% @9 H  _, w
  2.     '$set' => $values
    ) V4 B7 N# R6 w( f
  3. ,[
    7 L+ o  a7 ?, G7 J: ^) q0 Y
  4.     'multiple' => true//多条,单条false) r% V8 V( Y( d5 l% T
  5. ]);
复制代码
  • 0 {) _9 Y: U* y" m% ~' r
  1. $collection->updateOne(
    & z8 T5 d) _  J: h& T
  2.     ['state' => 'ny'],* `9 M8 [0 h2 S9 e% b
  3.     ['$set' => ['country' => 'us']]
    ' P# O1 W! X+ E' Z! f
  4. );3 _  p& s& {$ g& w* j' ~5 l
  5. $updateResult = $collection->updateMany(/ u. I, ^- U1 E5 V4 K
  6.     ['state' => 'ny'],( k; W' B9 x1 [* D! \# }- S
  7.     ['$set' => ['country' => 'us']]
    ' {+ r5 X% I. s. D3 c
  8. );
    ! r8 U! O+ q" ]; B( v# m
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询

  • 6 J/ \; i- J( N, g3 y; ]' S6 h* ?" h
  1. $cursor = $collection->find($condition, [
    ! Y, Z& a  C$ R; t8 t: q8 x
  2.     'name' => true//指定字段" m% i1 i+ t- X: z
  3. ]);
    8 `6 V: L" @, M$ Q( H0 t# K3 F5 M* \
  4. $cursor->skip(5);
    ' S3 W  F) o6 A: t( d3 p
  5. $cursor->limit(5);
    5 j8 ?5 ?1 n* x9 ?
  6. $cursor->sort([. [7 F6 F, x7 ^8 R8 }8 L/ L1 p) Y$ F5 G
  7.     'time' => -1( l( l  H) F, P5 f% i5 R- x
  8. ]);
复制代码
  • 1 W: R) K& g9 R( Z2 j
  1. $cursor = $collection->find($condition, [
    . \, p1 Y) |% D/ D, b
  2.     'skip' => 5,4 N8 {- c( k; ?' _6 _" x
  3.     'limit' => 5,
    3 x$ @9 A; E5 Z3 f# `
  4.     'sort' => [
    : m; z/ y! m) Y% }- @
  5.         'time' => -1$ \/ X+ ?3 A8 ~/ l# b7 ~
  6.     ],//排序
    ! |+ c( f8 V. B
  7.     'projection' => [1 G9 ]1 R$ `& M  R+ H* K
  8.         'name' => 1//指定字段* k/ E7 b1 y) h. L  H( M) M: c4 [
  9.     ]8 `/ R9 W; y% U" L: k
  10. ]);
复制代码
5.删除
  • ' M' F8 i4 C  r  A/ K
  1. $collention->remove($condition, [
    $ j; @5 w, e: O3 i" a/ ~/ u, s
  2.     'justOne' => false//删单条
    ' y/ S9 w! z2 M: o. y+ G
  3. ]);! C9 T2 Y, `2 Y( Z) L
  4. $collention->remove([]);//删所有
复制代码
  • " |2 j6 E" N( p+ V# P! M8 a+ k- |
  1. $result = $collention->deleteOne($condition, $options);5 u: o7 l0 i5 C( m# t
  2. $collention->deleteMany($condition, $options);  q) j+ ^- V5 F' f, m

  3. 4 u1 Q7 p$ I2 i$ A
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([" z8 c; M) a' |
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    5 Q5 w; j: G6 Q/ D; d
  3. ], [
    1 M% ?- V& j9 y7 B4 p5 V* x
  4.     '$inc' => ['id' => 1]//自增
    % T* f: l& c1 G* J; f
  5. ], [3 y1 K6 X& Y, P3 t9 }
  6.     '_id' => 08 t  n7 A8 z5 X/ r+ I: ~
  7. ], [
    9 d. {9 J+ _9 x: z4 @, U( M
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    : P0 o7 e4 K% b4 R1 w
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([- x; Y% ?2 v6 @7 \& \
  2.     '_id' => $tableName
    : k; E5 Z# v6 d2 C& o( B
  3. ], [
      f# j+ _" ]0 `
  4.     '$inc' => ['id' => 1]
    : |+ R- F% U/ v2 }  p" l
  5. ], [" O. v5 J- M3 p  Q: }
  6.     'projection' => ['id' => 1],, v; A- V' t6 n8 I9 b. H
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    # R3 j- `( A7 h+ _; L9 x
  8. ]);
复制代码

9 {1 R. J) X: j4 O: Q/ f: I7 h1 P; ~4 B
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-4-30 19:58 , Processed in 0.055608 second(s), 19 queries .

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