|
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
1 [- J* A" @" M/ |" x/ A5 u
! B, ~" N0 E- t- use MongoDB\Driver\Manager;$ Q- `; c) M m' O2 l7 k
- use MongoDB\Driver\BulkWrite;0 I9 \! z% S3 I( n
- use MongoDB\Driver\WriteConcern;
7 f, o0 ]/ G( k, H% I# Q/ H - use MongoDB\Driver\Query;1 f. e; m2 G& k
- use MongoDB\Driver\Command;3 S, T4 J. c/ }, b( E! ?
/ N+ w/ t3 j- C# A( E( o- a- class MongoDb {3 k5 R9 H9 I' Q
- 9 B$ W6 i) X. V3 ^; R2 F
- protected $mongodb;4 d" C% I. o. k# @9 z9 P$ q5 X
- protected $database;. v& h/ B9 `% x b
- protected $collection; u8 m. d* n# ~- I6 w! b1 _6 j
- protected $bulk;$ W6 j; K1 @9 c$ z8 Z1 C
- protected $writeConcern;
j4 K# z9 h+ `% \0 E& H0 l - protected $defaultConfig. Y8 \, x1 }7 U* A4 X
- = [1 s6 ?! M/ B$ p& k. h0 C6 u
- 'hostname' => 'localhost',
* c# z: S8 W D- H" N- [ - 'port' => '27017',
8 B& y# [0 ~! o - 'username' => '',4 l$ I0 v( c0 x: b+ J9 O. F1 L1 `
- 'password' => '',
! O3 b* D# J/ p- M: z - 'database' => 'test'1 k% _' }; y. w! W3 g9 M, E- ?/ x
- ];
$ {6 E+ _, _/ N6 S7 Z' E - : o3 a7 P" t ?( H
- public function __construct($config) {
# | T3 O V2 X! r d+ M' R7 H$ H - $config = array_merge($this->defaultConfig, $config);* Q7 k& g( I; R7 l
- $mongoServer = "mongodb://";% ~) j' B* b5 v* g
- if ($config['username']) {
9 O0 M1 V8 \; ]. V# K - $mongoServer .= $config['username'] . ':' . $config['password'] . '@';2 j n$ f4 v; s. Y
- }# F) [! v% ~0 |& f1 J7 G
- $mongoServer .= $config['hostname'];9 [, a7 H* a1 H. A2 Z( T
- if ($config['port']) {6 O% n7 o# @+ ^, A
- $mongoServer .= ':' . $config['port'];' X& c: }1 j$ j" o+ ?9 H3 i' l- D9 ~
- }) m m- h) L3 u+ @ S
- $mongoServer .= '/' . $config['database'];
) W3 r% }2 ?/ n' m - 1 \/ ^! p- ?. r9 r& M; V2 R
- $this->mongodb = new Manager($mongoServer);& w+ S0 k, P6 T$ i
- $this->database = $config['database'];
8 V' D% I% i4 m0 p- @6 K# U! c. b - $this->collection = $config['collection'];# e9 J4 E: y5 t
- $this->bulk = new BulkWrite();
4 f/ Y9 N! J4 p - $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);4 @ X& b& e! N D' k8 G# t) l: g, T
- }: T* v- m5 E& ^; Q
1 d j# O2 S1 k- public function query($where = [], $option = []) {6 V: O/ w/ T5 j5 K5 J" ^2 f: @& r
- $query = new Query($where, $option);
; e* @1 g- f9 @. U2 M0 \) r+ R - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
( T3 Q4 u/ w6 {* ?3 n3 S - / L3 [$ Y$ ?! ^: F& x% Z8 [* |. c& w
- return json_encode($result);
8 ^7 c. G% G @% O( f7 ~7 B - }
3 C2 T. q) W6 i6 U% ~4 a) f
+ G# B, w$ F. M- b* w& r ?6 D$ }1 x" \- public function count($where = []) {8 ]- O f9 t: D: W' E5 @
- $command = new Command(['count' => $this->collection, 'query' => $where]);
6 N5 m; j5 F- V% ]6 l - $result = $this->mongodb->executeCommand($this->database, $command);
! c' l9 Q" a4 o# x1 e+ F- }8 ~ - $res = $result->toArray();
+ D4 i, p6 k- J2 O% p6 [6 R - $count = 0;
3 C8 ~( u: ~7 r) C* w4 G - if ($res) {4 A" d s2 Q+ H8 ] u
- $count = $res[0]->n;/ O: j1 e+ H3 `1 H5 n
- }3 k$ \' @2 G: f" q& e
- * T7 }+ k: j8 y) h
- return $count;' L/ T: o" ]+ C/ m, e/ Y
- }
- h6 v" i) V! m% v9 t! U+ H
0 L' Q0 V& d. X# h L+ K2 X- public function update($where = [], $update = [], $upsert = false) {, r. g# ^/ e/ x- ~/ r
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
h0 j7 V1 I4 s! X, S" s - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);& m( P6 L% H: x$ ]) g2 X! E
2 _ C3 j+ P1 z4 Y- return $result->getModifiedCount();& |- B) ?. e: }% q' U
- }* C3 u5 X0 w$ s, U
- $ i$ T) o$ m3 @2 s* J L
- public function insert($data = []) {
C: m9 m3 M/ W - $this->bulk->insert($data);2 Z" A% g4 u3 q' G% W
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);6 V! `4 b: C% |) N n
2 i& |) {% k1 ]- return $result->getInsertedCount();
7 Q; Q+ f1 d: c3 B; c: J- ~ - }
8 H v0 v. { T
% }, j B2 U1 Q; R4 E- public function delete($where = [], $limit = 1) {. [3 ] _9 E9 K& f* v
- $this->bulk->delete($where, ['limit' => $limit]);0 o. [# A5 j7 z1 [
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
% r; w& z$ l; u% ?: ^3 O1 v } - 8 S3 ^, u. s& h3 {2 _
- return $result->getDeletedCount();3 P, v) o+ m5 ^& e& C
- }
0 S* v# o2 E7 n8 B - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原- n1 j& E" r# J/ m, n3 u. j. [& k
2.新增- 原- Y. }) N$ P6 p% q! ?% V
- $collention->insert($array, $options);
复制代码- 新5 {5 ^. x7 i( N( |4 H8 p5 _
- $resultOne = $collention->insertOne($array, $options);//单# b0 w& X0 a2 |* x, Y( r6 K L3 g) J
- $lastId = $resultOne->getInsertedId();- S: q: f3 p0 z: a
- $resultMany = $collention->insertMany($array, $options);//多
* q. J- {, T, a - $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [$ z! Z `4 y. `
- '$set' => $values4 j9 ^5 }% Z+ T4 m2 W
- ,[
) h4 I9 T2 ~6 Y, Z8 q0 E - 'multiple' => true//多条,单条false
( d% h# z" p# O% p1 }- b - ]);
复制代码- $collection->updateOne(
) q+ T; f S& f) Q% \! s; D - ['state' => 'ny'],. g& [, j* p/ Y" U
- ['$set' => ['country' => 'us']]
2 Z$ x1 O8 _/ N( M1 F* ?! Q - );; G- t4 {2 i! h' Z; G
- $updateResult = $collection->updateMany(
" j u6 k R' j9 o( g - ['state' => 'ny'],
, D* R* ~0 [$ g/ }/ u! n+ c - ['$set' => ['country' => 'us']]5 w5 m) S( q: N8 T# O- O
- );' R/ R( \% ]) A$ }% I8 ^6 F" r% y8 ]
- $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
- v7 }7 J' |$ T# Z5 N4 `9 Y2 @
- $cursor = $collection->find($condition, [7 L, ^7 `4 R2 }5 t& z% v" R
- 'name' => true//指定字段5 f* o- x1 e `: }& _4 Y0 A$ z
- ]);
( i- b$ I% M- ~8 |. v* O; X% U! J - $cursor->skip(5);
" c" |- s% u: ~3 N; t5 D" w - $cursor->limit(5);( F% ]2 I4 a8 `6 n- K
- $cursor->sort([" T* m0 [1 _% U; A
- 'time' => -16 R, q; E. g$ k( @
- ]);
复制代码- 新
o& d% r: ]! d; q! C! r- B0 B$ H, u
- $cursor = $collection->find($condition, [ W. @8 q f8 [8 L! J( e
- 'skip' => 5,) P1 |/ ^0 N* o. a
- 'limit' => 5,
% Z. ^! {3 p; X6 i$ k/ J* J, J - 'sort' => [5 d' q: J1 @# }4 f9 U
- 'time' => -1
6 \ x% f' m. H) B- H# Y" b - ],//排序
# W* |+ m) `7 r% k1 B) r- I - 'projection' => [+ B0 g4 m! f% h
- 'name' => 1//指定字段; |2 \, G$ B z# L( C
- ]& w4 Z( o8 J7 H v
- ]);
复制代码 5.删除- $collention->remove($condition, [+ E: ^0 e. l! X9 i$ I1 |( C, O
- 'justOne' => false//删单条3 @2 c1 l/ M, A, C& `+ {
- ]);$ p i8 j9 f2 ^/ c
- $collention->remove([]);//删所有
复制代码- 新
) V0 m1 ?- g. S* ?9 W$ b3 |2 E2 M
- $result = $collention->deleteOne($condition, $options);
9 i- x: W' D0 b' q* @ - $collention->deleteMany($condition, $options);
0 `1 K) d% T/ _* b: {# l! t
|: h9 e( ?' p$ `- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([
' A6 w# c# R* v( U$ D - '_id' => $tableName//我在自增表中用其它的表名作主键. A5 ?# S6 l( Y+ R! |/ o
- ], [
- s% ~8 u4 z6 T( r( r0 Q; t - '$inc' => ['id' => 1]//自增
7 f) i- x, I$ N - ], [$ ~% b9 ?$ P& K1 r1 q8 n
- '_id' => 0
8 Q+ p& l# H2 O6 c' A* o - ], [
0 p+ G# l( W* j# r) x% a - 'new' => 1//返回修改后的结果,默认是修改前的
9 A8 l% U* k0 ] - ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([
+ s' I8 i- T9 R5 G - '_id' => $tableName. {, R1 @+ Z* O( ~% m
- ], [
* J. b( E8 Z$ B/ I( B, z* A# F - '$inc' => ['id' => 1]- \5 V X# C: p" t' h ^3 N/ d
- ], [% I4 V# e. r5 Z" |$ O
- 'projection' => ['id' => 1],! P* c! ?# b! Y; g* O/ k. @$ ]
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
- x- _- W3 \: x' P4 U% J - ]);
复制代码 9 G: `3 U1 r* P- |, t8 b5 U9 D9 I
. F7 m% S+ _6 Y1 ~ |