使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
8 ]. q' `$ k$ @4 ]8 }8 z$ i+ D
U7 O6 I+ c: t; o! v& d- use MongoDB\Driver\Manager;4 w, Y* o# I( e( O% O
- use MongoDB\Driver\BulkWrite;
3 M1 d8 e+ [) M; ^& K - use MongoDB\Driver\WriteConcern;
+ B* T- n$ E$ J: s: Z - use MongoDB\Driver\Query;
3 P7 ^! P d( a+ M2 Z* h* S - use MongoDB\Driver\Command;- w2 v7 N4 C! e2 ^/ V$ f' B0 l
0 M- u& X" {; T, T- class MongoDb {3 Z& m1 ~8 R' |3 y
' L4 \ Z: ?: I, C3 t- protected $mongodb;! `* o9 Q/ }8 X
- protected $database;! {+ c% O( D8 v; ]2 W( h
- protected $collection;2 Q) I8 k4 K: X
- protected $bulk;
, d8 k" l$ u$ v. |- n' [ - protected $writeConcern;8 j7 U; p& q! W6 h
- protected $defaultConfig
0 l, B; `6 b4 A+ C% G/ f/ @ - = [$ ]7 {5 A# @ y+ e$ x4 @ m
- 'hostname' => 'localhost',5 {) |! S* u0 y0 e5 }. k
- 'port' => '27017',; Z- B6 I. q9 W) J f$ J+ g2 N
- 'username' => '',) F( L$ K( A* O, e
- 'password' => '',/ S! j1 ?8 i4 h/ L. t$ X! H# E% G3 {
- 'database' => 'test'
- X6 J; Y% z% U) s7 r - ];
; q3 n/ c% U0 V V* b% ^5 z
8 g" k0 U# N! o( t( [7 z- public function __construct($config) { Z4 [2 J0 D" j
- $config = array_merge($this->defaultConfig, $config);
% ~' U, E2 p+ x, r - $mongoServer = "mongodb://";' ^: E( X5 w5 F% T
- if ($config['username']) {) [9 S, z5 |3 m. m( A, v" X
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
$ l7 Z! h# f: f; Q - }
- \1 A+ i6 _# ^% N" X9 r- b - $mongoServer .= $config['hostname'];4 m |' I- J: ~! s. F
- if ($config['port']) {' C5 j; n8 K& y5 E4 J6 O8 N" U
- $mongoServer .= ':' . $config['port'];
( I3 @) m& O/ k2 z8 i" a# o - }% H, A r. B5 G: e" a: s: A
- $mongoServer .= '/' . $config['database'];
- M8 n; y3 V% g5 r" F* H' t. y
# t3 ?2 _" R' m t9 J3 M" O- $this->mongodb = new Manager($mongoServer);
2 m( B8 I R3 q8 {, n - $this->database = $config['database'];
v0 ?' S0 H- j3 } - $this->collection = $config['collection']; w, Z) _( f& `* i: q0 j9 W
- $this->bulk = new BulkWrite();5 E J5 C! a4 I
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
- K, r3 D# S- E# T - } a3 B- }- N B# ?
- - O# D2 f* }4 P
- public function query($where = [], $option = []) {; o7 L/ s; l$ m5 J: h6 Z
- $query = new Query($where, $option); G0 ^* Y0 k, W- @
- $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);1 E+ d# V: D$ {9 X6 ~6 B% Y$ `
- & h, `' D. }7 T) v& m6 V
- return json_encode($result);) o j" y' I& U# R% a; Q
- }
2 ]% N" m) O R7 a- O - . Y7 d$ m* C& H1 z7 A
- public function count($where = []) {/ K7 M. s8 q% A' T
- $command = new Command(['count' => $this->collection, 'query' => $where]);
1 Y K$ z" z3 W1 w- g5 n - $result = $this->mongodb->executeCommand($this->database, $command);
2 w& d# M; t/ _1 X - $res = $result->toArray();
. y H+ R9 u K7 D# w9 Y - $count = 0;$ Z5 C. o+ J. K% r5 O; D
- if ($res) {3 s a# q5 I. \/ X3 S2 d1 W. t0 ~ \
- $count = $res[0]->n;
0 x, ]9 ^3 j! ?+ f - }
. S3 O# J1 P( S* n/ o
) w4 Q) s' {2 i6 _9 ?; @1 L- return $count;3 i3 E: `) p9 [% L
- }
" R6 y9 Z- e. E$ c- E3 g8 \5 X1 r; k - % H+ [& N U3 t- A3 k' a2 A
- public function update($where = [], $update = [], $upsert = false) {! h9 n- j) x4 a: r) s U7 c0 s
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
' M: B; a. @, L# ?& Z - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
' E P4 M$ T. s0 A a1 Y; I+ L - : p& |- h ]. [9 H( e2 y/ ~9 s
- return $result->getModifiedCount();
# S7 Q" W" \) d% j1 a - }
& L( s( E) f5 U) [" s6 B7 `0 s - 7 I8 y+ A) W- A6 Q j7 n; P
- public function insert($data = []) {
: p" W w5 O. T4 ^9 V) _ U, m - $this->bulk->insert($data);
* E6 ?5 \5 E- x2 r" k; F4 | - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
. E8 j* w* c7 E( ~: e - % ^8 F) \; H5 r: p/ B/ b; o
- return $result->getInsertedCount();% ^. {/ o4 q* g# C, @+ ~3 z
- }5 o9 `9 ~/ S8 V; g2 i1 Q/ o
- 6 U; T; P: N. n7 G7 `6 X
- public function delete($where = [], $limit = 1) {! H1 A$ s3 o. y
- $this->bulk->delete($where, ['limit' => $limit]);. L" O$ b. O1 b, Z* |7 G: _( o, y
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);1 k8 ^. E) X, K1 t2 F% U% c* \- ]
- ; b* l' V, ]4 V4 f. X
- return $result->getDeletedCount();
2 @* `6 ?5 S3 x1 ? - }' J s* F t3 f& P. ?9 ?! r
- }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接2.新增- 原
( f! o) J! _# M/ ]+ w) ?& B- F- E
- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单7 m. K# |" r9 g2 J; y8 t9 `
- $lastId = $resultOne->getInsertedId();
# T. ]' ~% p6 R! r) u0 o* ~ - $resultMany = $collention->insertMany($array, $options);//多' B6 t9 Q3 C# q g5 I
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- 原
( _9 i2 i2 y" }% y% \. H
- $collention->update($condition, [
; J: x) c4 Y3 G6 p$ F - '$set' => $values
+ F" G4 Z1 Y5 ~6 s7 R - ,[8 _; b* T) ~5 e9 D4 F! B4 A6 _
- 'multiple' => true//多条,单条false
) m' I$ J/ n8 H" Q! H% S - ]);
复制代码- 新
0 l' ?8 q' K& @: S4 y9 W$ H
- $collection->updateOne(' u* l* G& o! l4 N
- ['state' => 'ny'],
" ]% K v- \: |( {' Z - ['$set' => ['country' => 'us']]# n. }& r! c& P
- );2 Z+ f" ]- D5 W+ T( y6 T
- $updateResult = $collection->updateMany(
9 q, o" H2 x# v* m* l2 P2 [ - ['state' => 'ny'],
; r8 ]" D' ]2 o/ N ] - ['$set' => ['country' => 'us']]) m: v4 ^* ^( Z0 E
- );
6 U8 n4 z0 `5 j& x% e/ y - $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
9 k! S# F; `) A2 K) X4 p
- $cursor = $collection->find($condition, [
6 v# u1 p# i1 ?4 S- Q& R - 'name' => true//指定字段7 s1 h k$ V$ k8 v4 T- z4 \9 G I
- ]);
6 W9 G/ h' P) h% } - $cursor->skip(5);& ]; E4 e& Z1 S8 M
- $cursor->limit(5);+ ~. R# Y Z6 b; m$ Q7 G
- $cursor->sort([1 Y$ @# H" E0 z+ [: X
- 'time' => -1
, y2 l# j7 i. ]# @( O5 Z5 ] - ]);
复制代码- $cursor = $collection->find($condition, [
$ W- e; y t0 ?5 Z3 B - 'skip' => 5,
: Z. o6 g: c+ r+ h% Z; E& [3 ~6 | - 'limit' => 5,* `% ?" b; [# ~. x a; i4 D
- 'sort' => [
% [2 j: w3 b6 ]$ f Q* F2 e2 U' D" {0 }6 S - 'time' => -1% W4 x, H2 @$ k2 [
- ],//排序/ p8 J2 b% T' L- y
- 'projection' => [
! n/ ?" K/ R5 A8 Y$ F2 T, r/ q - 'name' => 1//指定字段
& ^$ m5 S% _2 K+ B& i2 E - ]& b7 ^8 x5 _/ V" x6 L Z& c/ R
- ]);
复制代码 5.删除- 原
. {( i0 `& w# @+ Z) `) D1 @+ F
- $collention->remove($condition, [, A; T! F0 Q I1 i5 ^4 W
- 'justOne' => false//删单条' I; s) _# w* Q! x) d3 T5 ?6 r; z* L
- ]);+ Q6 b5 Q8 ^, u5 R/ `6 x |
- $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);
* E. U1 ^% l3 Z, q* V, l. u: k$ C - $collention->deleteMany($condition, $options);
* ]. n) A1 A Q: n: W* h - % e$ A/ Q+ Q4 z. o8 |& A6 s: x
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([1 j1 j3 z& T7 d/ P$ W6 |% Q. ?
- '_id' => $tableName//我在自增表中用其它的表名作主键) t" T w& Z/ ]3 O9 E! b
- ], [
T2 [1 T8 D! |/ p1 x - '$inc' => ['id' => 1]//自增
8 S- k- p0 b7 G - ], [9 X0 [7 X% |2 r6 m! h# J. I
- '_id' => 0$ h- B5 F3 L6 Q1 ~) }3 e) W* d
- ], [' I) |( u+ J' n& x4 E/ T% e
- 'new' => 1//返回修改后的结果,默认是修改前的
" H* E3 U8 O2 ]; x$ l- D - ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([
: d* K; ]8 u% a# }$ |. F - '_id' => $tableName
! r E: B- `* i, ~, P( G1 w" p - ], [& {& _' N& }6 Y' t! }
- '$inc' => ['id' => 1]' j% h1 f8 @6 `: ]* t n
- ], [4 w, g. y# Z$ R- X/ y T
- 'projection' => ['id' => 1],
$ X& Y* G1 m7 p$ } - 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER c, {/ ~1 d' S2 J! v
- ]);
复制代码
4 g6 Y4 A$ Z2 V$ b7 k8 t0 h2 i3 o
) J6 V0 T7 V, J5 H |