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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 16552|回复: 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
      b  C. {* K+ l- p6 B3 f
  2. 2 S2 l) q+ W/ n2 P5 V0 _, @4 t" s
  3. use MongoDB\Driver\Manager;4 M# m9 `' |, W0 x+ e
  4. use MongoDB\Driver\BulkWrite;
    # e6 M/ J0 S' b1 m1 c; x
  5. use MongoDB\Driver\WriteConcern;
    7 O2 q. `! e7 \+ A; K" ?  B6 R
  6. use MongoDB\Driver\Query;
    8 j+ Q& P& u4 R" y6 ?
  7. use MongoDB\Driver\Command;* y5 j5 W% p. i+ A
  8. 6 `( x' M; t  F
  9. class MongoDb {
    9 {2 T8 f) n: w1 a' y
  10. 9 d, \; }9 K: |7 q: Y9 l
  11.     protected $mongodb;7 U5 o# x2 C+ K% c& T/ z
  12.     protected $database;
    " ^* P+ e% l5 h' Q+ l( f
  13.     protected $collection;
    / ~' [  ]% Q7 n9 B8 D. U5 _( ~. n
  14.     protected $bulk;! J. p/ c3 k) Z- K( a/ \
  15.     protected $writeConcern;
    7 L- n( D5 b+ o2 |) L
  16.     protected $defaultConfig
    7 J' O3 T) ?; Z$ E8 H5 p$ T$ U' s
  17.         = [
    1 T& ^+ E! ^6 X& n" m' i
  18.             'hostname' => 'localhost',
    - E0 w5 {. G! i/ Y. J
  19.             'port' => '27017',3 X3 Z$ r* R# P  p% p
  20.             'username' => '',5 {& S) b" c! f/ D4 [7 [/ H
  21.             'password' => '',6 F' B* u1 l% t
  22.             'database' => 'test'
    8 P0 z+ d1 q3 }( q) a3 B1 p9 @
  23.         ];
    $ B. R5 Y: r" ~2 r* I& N- ^. u! T
  24. . Q# E2 e. j* F, \' t1 J
  25.     public function __construct($config) {
      C6 W& A1 r4 C# S: @
  26.         $config = array_merge($this->defaultConfig, $config);
    7 k* n6 N7 z3 L* U' C8 A
  27.         $mongoServer = "mongodb://";8 d, }( H# W$ I
  28.         if ($config['username']) {& ?+ V! k1 c! l+ a  s) k
  29.             $mongoServer .= $config['username'] . ':' . $config['password'] . '@';0 U, V4 E) a( o$ ^3 }, D1 Z
  30.         }8 J9 C& Y/ N9 ~& }6 \' K8 F
  31.         $mongoServer .= $config['hostname'];; ^& e* t* |2 C) h( f/ o; Z" l0 M
  32.         if ($config['port']) {! S3 |+ `6 O* I; S, J, J
  33.             $mongoServer .= ':' . $config['port'];6 a% Z/ _2 Q: P& `
  34.         }
    / }) v# K! A* ]! H! v
  35.         $mongoServer .= '/' . $config['database'];7 r% z" U0 }- O- O+ _) c
  36. * n3 l! C; L" U1 ~* W
  37.         $this->mongodb = new Manager($mongoServer);& ^) w1 k& Z7 s3 [7 y) |
  38.         $this->database = $config['database'];
    % e/ Y9 g0 Q5 u* G. _' N
  39.         $this->collection = $config['collection'];
    . c0 `  A9 ^3 P$ x6 S; E$ p# C" G, l
  40.         $this->bulk = new BulkWrite();  a+ D6 l8 E7 a* l6 N% W
  41.         $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    % ^# c7 H) `4 z$ s0 \( o
  42.     }9 L3 i. M$ _( E2 K

  43. - e& p, y. ^; D
  44.     public function query($where = [], $option = []) {1 V( V: m) @) g$ o# X3 D
  45.         $query = new Query($where, $option);
    6 A$ Z' t7 V( H  x- a& A# e" v; i% a, k
  46.         $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);; I8 i$ N$ p, d6 D. n" j. v- c
  47. : G* `; l7 d4 Y$ x" S$ s# f8 s
  48.         return json_encode($result);
    * b+ t( a4 R/ e& i: P% G/ f
  49.     }1 |- o0 r+ X1 T3 o# C# I  v7 z- C2 K. }
  50. & A2 a3 x  D, g
  51.     public function count($where = []) {
    % q$ J, C* C3 |8 M
  52.         $command = new Command(['count' => $this->collection, 'query' => $where]);
    0 D( {* E2 l0 j0 ]" q8 J
  53.         $result = $this->mongodb->executeCommand($this->database, $command);
    6 Z/ E, x0 E& X) D
  54.         $res = $result->toArray();
    , ~9 a: a9 [- q2 I2 v2 q
  55.         $count = 0;, E+ J" d9 S; x8 N) J
  56.         if ($res) {% D. u% K* w. h8 R* t; P' b
  57.             $count = $res[0]->n;
    " h+ h) L7 {  {1 X' m0 e& u- B
  58.         }% g/ u/ K* S2 L

  59. $ K( Y( F+ k7 E  s9 Z0 P
  60.         return $count;5 ^- Z- F+ M$ s8 D. `
  61.     }$ d5 R2 D) \! u. ]. v% H
  62. ' Q9 m+ ^/ f" ^3 X+ N7 g
  63.     public function update($where = [], $update = [], $upsert = false) {+ _5 e& o, e3 i; H7 C# s
  64.         $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);1 g. i; Z: v! H
  65.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);) v7 M  n, N! Z1 I# l
  66. 0 C# {0 |% s. t0 `; _! k
  67.         return $result->getModifiedCount();
    : Y& V% }) V' j# V
  68.     }
    $ f7 C+ X9 z" n! T
  69. / F. _& ]) ^6 ^8 U: h$ o
  70.     public function insert($data = []) {4 y4 N$ x- {. r( U
  71.         $this->bulk->insert($data);
    ) u! D7 R) P' g( F( ]. w
  72.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);" `. v5 r# S+ s
  73. 0 `. t% S! i/ y3 r! G% I' ?: V
  74.         return $result->getInsertedCount();/ o8 c  w- S. `/ Q+ B
  75.     }& P  W; J) r7 Q' p8 |2 ~+ T8 ^3 Y. d

  76. 6 _( K: F$ @) i
  77.     public function delete($where = [], $limit = 1) {/ W4 D3 t3 _6 K9 g" @
  78.         $this->bulk->delete($where, ['limit' => $limit]);
    + C7 T# G5 @- L6 ~3 H; b+ F
  79.         $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);! l& ^+ C7 K+ o, J
  80. 7 [" Y( U0 P# A5 m+ e4 X
  81.         return $result->getDeletedCount();/ o$ Z( g  O$ r  g
  82.     }
    / e& [) \0 h; s: n) K1 {
  83. }
复制代码
这样的语法和之前差异太大,改动不方便,换 PHP MongoDB
MongoDB 库1.连接
  • + H" v9 g7 M' @! {. T( @
  1. new MongoClient();
复制代码
  • - K/ }8 z/ `5 `7 I! [  n! q* Y1 z
  1. new MongoDB\Client();
复制代码
2.新增

  • . D/ m2 s8 r) p9 x
  1. $collention->insert($array, $options);
复制代码
  • ' q2 M$ U; e4 f0 F' T  H
  1. $resultOne = $collention->insertOne($array, $options);//单) _" D5 s0 q  |1 K: G
  2. $lastId = $resultOne->getInsertedId();  A& `! l& f1 o& U- h1 G
  3. $resultMany = $collention->insertMany($array, $options);//多+ v- u3 Q- @: M  }% T
  4. $count = $resultMany->getInsertedCount();
复制代码
3.修改
  • ) v" j. D" i1 A& }: ~" U, H( r
  1. $collention->update($condition, [
    - ^/ E+ C# B  s3 w2 E% I1 j0 m6 |
  2.     '$set' => $values
    0 o1 Q0 ?. i  y9 c! Q6 M) c
  3. ,[
    5 Q! K- P( g5 N- D* j0 f) p2 e
  4.     'multiple' => true//多条,单条false
    : X3 [1 u" i- R$ @4 g' K
  5. ]);
复制代码
  • - ^9 {6 [: H0 Y' r$ q) x- M
  1. $collection->updateOne(/ D* s: C% R- x! G9 l) A$ {
  2.     ['state' => 'ny'],
    * h# I) \3 [- R, D# T( r
  3.     ['$set' => ['country' => 'us']]
    / D2 V# g" l1 c! ^
  4. );
    ) F4 P% _4 L8 w) \/ I
  5. $updateResult = $collection->updateMany(
    8 Z3 x/ `# i8 f9 f2 a2 X) Y4 Q
  6.     ['state' => 'ny'],, O2 C/ g3 M2 {8 \9 P/ i7 {1 ~3 l, D
  7.     ['$set' => ['country' => 'us']]
    + e3 a% v* B/ q" |
  8. );* F) P1 T6 |& }4 ?+ Z$ u
  9. $count = $updateResult->getModifiedCount();
复制代码
4.查询
  • ( U* |! W! y5 g& l" F  ^
  1. $cursor = $collection->find($condition, [% T' ?1 w" }8 y( x' {- a  l5 ]' H
  2.     'name' => true//指定字段: U  S/ C% }; I' b& T
  3. ]);
    ) U' n& a) B% D' |) V; z; o8 }7 \, C
  4. $cursor->skip(5);
    ' F" I0 A# U6 o5 N% J) O% s: N
  5. $cursor->limit(5);$ m8 {! A6 i) L* \/ {
  6. $cursor->sort([6 f6 x( S  q. e6 c
  7.     'time' => -1" \  R3 ~6 l1 {- @& T- s
  8. ]);
复制代码
  • $ T+ g+ \- c  w8 r! U) V1 e& W
  1. $cursor = $collection->find($condition, [
    ' r% M. I. J0 h
  2.     'skip' => 5,
    . E; N; T3 k* k  c1 j' b, M
  3.     'limit' => 5,8 |. \# z7 i' P7 z6 u
  4.     'sort' => [
    0 G5 t8 E3 ^5 z6 |
  5.         'time' => -1
    ; ]& W8 ~) B7 A$ M( J. Z& \
  6.     ],//排序
      l- L1 N* q  T; u/ [  @9 R9 q
  7.     'projection' => [
    , j* j7 v. i9 w: [
  8.         'name' => 1//指定字段( F; [( A1 F/ ]2 I$ y, ^
  9.     ]8 M9 ?  d; t2 G: |$ ~
  10. ]);
复制代码
5.删除

  • ; j. @* r3 B8 ?- n6 x
  1. $collention->remove($condition, [
    + a, z# j  M  K8 O/ V; M! q
  2.     'justOne' => false//删单条
    & U- n0 o8 w( k8 z) u: `2 `
  3. ]);) M1 C7 f" l3 x8 j7 p# K- E
  4. $collention->remove([]);//删所有
复制代码

  • ( W# l2 B# ], k+ \/ @5 F6 I: ?
  1. $result = $collention->deleteOne($condition, $options);
    3 H( j- i5 h3 p) P- g0 z+ g
  2. $collention->deleteMany($condition, $options);
    7 q) |/ S, \; q& t! l3 a
  3. ' M$ x/ x. D# [4 {' [+ q7 u
  4. $result->getDeletedCount();
复制代码
补充
有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
  1. $collention->findAndModify([
    4 |9 A' T% G* G
  2.     '_id' => $tableName//我在自增表中用其它的表名作主键
    2 b( ]7 `9 e  I/ b
  3. ], [3 f: o9 \3 y" X9 k
  4.     '$inc' => ['id' => 1]//自增) r; F, ^# j3 V5 x6 L! N) h
  5. ], [0 }4 n% z/ |! x1 F2 @" i8 B% V
  6.     '_id' => 0
    5 G) k0 q1 M/ M! U, h1 ?+ |
  7. ], [2 U7 |! g2 _% D, ^( o) s
  8.     'new' => 1//返回修改后的结果,默认是修改前的
    - @, S9 p) |+ g4 n
  9. ]);
复制代码
现在使用 MongoDB 库的话需要修改为:
  1. $collention->findOneAndUpdate([
    9 }1 }% ~- D* \. r7 o. s
  2.     '_id' => $tableName
    & E. V& S; i+ U2 \
  3. ], [
    " q; J; J) i' F4 t+ P( k) H
  4.     '$inc' => ['id' => 1]$ x5 Y- g4 r+ s( H
  5. ], [
    1 j$ O9 t( Z/ j) x  U
  6.     'projection' => ['id' => 1],$ E3 `$ {' p2 d, O- }, W
  7.     'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
    4 Z( \" I0 Q0 P2 R  d, G) I
  8. ]);
复制代码
4 ?+ B" V4 ~! _3 M

, W3 I( f# P) M) s9 @9 D
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-20 04:17 , Processed in 0.060952 second(s), 20 queries .

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