cncml手绘网
标题: 升级PHP7操作MongoDB [打印本页]
作者: admin 时间: 2019-3-19 14:24
标题: 升级PHP7操作MongoDB
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。
但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。
MongoDB 驱动如果使用原驱动的话,大致语法如下:
- <?php
. }! x9 W, i% j8 D* s; I - : [( H" L% R, `
- use MongoDB\Driver\Manager;/ g) h4 B- s& {5 L' j2 k6 c4 f
- use MongoDB\Driver\BulkWrite;% W# O& W3 b* D' ]+ s) T3 f# B
- use MongoDB\Driver\WriteConcern;8 P) ^, k( R. c5 s
- use MongoDB\Driver\Query;
) p7 D, Z4 q& r6 A - use MongoDB\Driver\Command;
+ ^$ j; E3 i) E& T- A - 1 |* N4 h$ {( Z }! o
- class MongoDb {& B( C5 U- x$ M; y5 t( m! d
- 2 y( g$ c# `9 ^* g
- protected $mongodb;9 ~4 k8 R) F+ F
- protected $database;2 \6 a$ }' D$ t) {7 P/ d
- protected $collection;2 g) ~) n/ l; {) A0 q6 p
- protected $bulk;
! w( \$ o1 |5 w: T0 F$ v! L/ h X - protected $writeConcern;# D# Y' s9 \" K8 h* f- ~* V
- protected $defaultConfig
& F5 ~# e- ?! h - = [
7 e8 t( W2 f+ d - 'hostname' => 'localhost',
$ p/ i# M& P1 q8 S - 'port' => '27017',1 g0 N+ N. [2 G
- 'username' => '',
/ e% n6 L2 F2 a) I+ x - 'password' => '',1 ?0 w( f3 g" b7 u
- 'database' => 'test'5 @# ` F$ g! o+ K- E
- ];2 n: t# |2 L3 N; U0 [
- 5 I, k8 s+ Z6 C; Z( }( r+ U
- public function __construct($config) {" n# z' b) F% O* E1 B) m3 e0 L- y& z
- $config = array_merge($this->defaultConfig, $config);
$ `, y) g9 {5 O6 {" M - $mongoServer = "mongodb://";5 v: s7 d, s% d5 c7 ]% M: _
- if ($config['username']) {$ I% i3 |! T9 K' f
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';: W5 ]2 E5 g. V) q2 b2 c
- }
" g! |( K- ?0 t3 t - $mongoServer .= $config['hostname'];, ~4 N* i+ ~5 i! n7 p7 |
- if ($config['port']) {/ P" n) [2 b; V' Q, `
- $mongoServer .= ':' . $config['port'];
, U- D1 t$ T2 j# Q - }
& @: K, X" B2 e - $mongoServer .= '/' . $config['database'];
) f' u% o6 f/ R$ L; c - $ ?- K2 r6 w& Z
- $this->mongodb = new Manager($mongoServer);# }3 \9 {: G! O! F2 X
- $this->database = $config['database'];( s! R8 `- K3 H4 q& K
- $this->collection = $config['collection'];# L0 z4 ?1 Q: Z$ E: n) I; U8 l
- $this->bulk = new BulkWrite();2 i5 r3 d7 |) C5 e
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
+ E A, J$ C" ?3 d) P - }
2 U6 D; @/ P7 V/ J5 L w; I
. e8 h, ~1 J1 x; x8 X- public function query($where = [], $option = []) {
- S/ c$ V* s" G$ _ - $query = new Query($where, $option);# l, V! P$ F6 i0 S( p0 T
- $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
" U/ X3 t# A& j$ {9 z6 e4 _ - . d8 I; O& Z$ Q1 G
- return json_encode($result);
5 n. C9 V( I1 F7 A' d - }- E3 |- j0 N2 P# `
- & y. j5 c# U, ~3 B; S
- public function count($where = []) {& w& Q0 C! @( f) o0 }$ @/ D
- $command = new Command(['count' => $this->collection, 'query' => $where]);
2 y3 a0 P6 @1 E9 C ? B+ k - $result = $this->mongodb->executeCommand($this->database, $command);6 h+ H6 u: a$ `5 G) \) K
- $res = $result->toArray();
7 c+ N) t5 I4 \# l# b3 ]; f# s - $count = 0;% x8 X# O. X: r6 z$ u
- if ($res) {3 a* H( Q4 R: [; Q$ w. y% v1 ^
- $count = $res[0]->n;
( X. V' d9 q2 Y* u, { - }
0 b9 B2 `2 a0 k( f9 O. e - # X7 F* N$ \+ _4 t
- return $count;
& A4 ~: v4 d" H) J2 X9 _( x - }/ I& u, x8 Z; r: e) P) n& m; T
4 [. Q& ^6 x5 I: S- public function update($where = [], $update = [], $upsert = false) {6 m" i, s& f* l& Y
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
/ l, A! f I* W+ d - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);3 r) p; N$ T0 { v
- o& P' d4 X+ ~3 O
- return $result->getModifiedCount();2 _$ Z9 w" w8 e- K2 g
- }$ `9 c2 H) `, S$ a$ J- W: [. T8 L
- . C" i. a, U; N( `% g4 U6 N5 f0 @
- public function insert($data = []) {
- s6 ?% S( p5 p$ O$ M6 k( W; Q3 j - $this->bulk->insert($data);
* R. X# q$ h3 R j' z( E - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
2 y+ X/ y2 u( c1 K& x3 i3 F
; U9 @9 T* H" M- return $result->getInsertedCount();: T$ M8 l0 d3 `% s d/ V
- }
" {4 V* {% D& L& C
9 M7 T) z9 c0 Z1 M! w- public function delete($where = [], $limit = 1) {; h8 I- Z$ P& }' N
- $this->bulk->delete($where, ['limit' => $limit]);
3 _! c, P% i0 r1 S* s" I/ p - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
' M! n. W7 F/ E
! i% o: T7 ^( ]7 R) E. H- return $result->getDeletedCount();
/ d, C k# O4 S' A - }1 E- [. O: [8 _' }, g2 u
- }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库
MongoDB 库1.连接2.新增- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单
& b' _9 x* U$ [ - $lastId = $resultOne->getInsertedId();5 Y \! {0 Q; F3 t7 t
- $resultMany = $collention->insertMany($array, $options);//多* W& b1 F8 s# C! V
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [
0 N7 V6 s! f J6 u) B$ D! c" m8 L - '$set' => $values
! ]( z8 r5 n/ B% I7 Z$ a - ,[1 Q+ t$ k2 ?2 M K
- 'multiple' => true//多条,单条false5 w; B6 d4 P: V
- ]);
复制代码- 新
1 K0 j; D$ p% j* M) N0 q
- $collection->updateOne(3 E' e: `. G% q
- ['state' => 'ny'],
, E$ V0 j* d. Z2 J2 p0 {" { - ['$set' => ['country' => 'us']]
+ n) w) t# H7 o- u3 h - );
4 @+ ]0 c- m o0 y' x7 @ - $updateResult = $collection->updateMany(
0 |0 `9 o( W; J$ q) p/ y - ['state' => 'ny'],
4 \ Y. p* @) J - ['$set' => ['country' => 'us']]
3 \% c9 f+ {7 e( [$ V y) t - );) b2 p: B( w/ @1 @
- $count = $updateResult->getModifiedCount();
复制代码 4.查询- $cursor = $collection->find($condition, [$ q3 c" t% J5 P% G' c& H
- 'name' => true//指定字段
b/ Y `. I9 P$ x- U - ]);
5 p7 x: k7 e6 Z% E5 B5 Q7 D - $cursor->skip(5);
+ D& Y1 T! |6 M; ^ h - $cursor->limit(5);
/ H' L& P X! h! S6 r - $cursor->sort([9 d0 U) c5 Y4 D! Q* O& @; X
- 'time' => -1) L9 |% ^3 W: `
- ]);
复制代码- 新
1 A" A6 G8 l# I1 L9 _1 j
- $cursor = $collection->find($condition, [) @: \5 d' F$ d% B) O
- 'skip' => 5,. R. X; Z9 \: z& f5 `) p
- 'limit' => 5,. D: H9 `, J t; H* Z4 J
- 'sort' => [* U' c0 @* [( e9 j" T/ }3 P
- 'time' => -1
# |4 x& Y3 i# E& p9 H' B$ ^ - ],//排序* K$ Z0 l# m* N+ e1 a/ v
- 'projection' => [) i6 s" A3 |7 |6 k- a# r
- 'name' => 1//指定字段
5 e& G+ f5 i+ F$ F5 g - ]
7 t/ s" W2 t" i _* c - ]);
复制代码 5.删除- $collention->remove($condition, [8 |6 r" a2 X5 q! ~, w* o0 Q
- 'justOne' => false//删单条. z* M( Y2 ?5 \8 p; ]+ v% ^
- ]);, g& `9 m3 e9 a/ I- w
- $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);2 T4 D8 @: L# d4 J
- $collention->deleteMany($condition, $options);
, V+ A, S0 X) B - & `5 ]* K$ @' z. Y' B& u9 w
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改:
- $collention->findAndModify([
9 Y9 B- w* e5 W5 g9 u - '_id' => $tableName//我在自增表中用其它的表名作主键& l; ~6 z4 H* D
- ], [( T+ w) c# G$ u# _9 k5 z+ p4 K
- '$inc' => ['id' => 1]//自增
9 i. X: ]* r6 M2 D5 U - ], [! s9 m- W- |6 z0 s% I
- '_id' => 0
! `6 e* }$ K% t* A/ J4 W - ], [/ i& e0 C" P: \$ p# l% f+ |
- 'new' => 1//返回修改后的结果,默认是修改前的
/ L0 @1 R' s) H% u1 @! o' V1 c X - ]);
复制代码现在使用 MongoDB 库的话需要修改为:
- $collention->findOneAndUpdate([
, c3 D# q# h0 Q7 e% L( ^( } - '_id' => $tableName
3 D+ A, k ]: p( V( F - ], [
Y! r" ?% h0 W: V - '$inc' => ['id' => 1]
! K, ?% A5 f1 O" v2 X8 s2 r. s; j - ], [
' D6 o5 `2 n7 J- x9 ]* F# l - 'projection' => ['id' => 1],+ \. ^; {8 C+ N% f3 z; ~) |4 X
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER( ? B! V- c* c
- ]);
复制代码 " `# p% M5 t( c' m/ B8 T
/ D1 D9 K8 I6 F5 b3 x1 [( ]
| 欢迎光临 cncml手绘网 (http://www.cncml.com/) |
Powered by Discuz! X3.2 |