使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
* l# {- a% _9 {. R
) j" \/ j: C& P6 X5 p/ M- use MongoDB\Driver\Manager;: z; F" P( Z/ n7 L9 X- v
- use MongoDB\Driver\BulkWrite;
) [; I+ p8 m* }) r/ ~$ {9 w - use MongoDB\Driver\WriteConcern;8 T. k' y" W% w# ?. s
- use MongoDB\Driver\Query;% G- H& N: `7 T7 Z" H" n
- use MongoDB\Driver\Command;
% U1 N t+ I8 H2 n; L6 G
& K; \ E% H$ @. s- class MongoDb {" K$ p& m2 n+ m. l
- ) D4 j0 F5 |3 o. a6 i
- protected $mongodb;) P9 U+ I' \ D7 x
- protected $database;
+ c- D: z. L9 z8 B' ] - protected $collection;
/ Y& `$ X. x" }: S4 C - protected $bulk;7 ?2 o; }$ z) a4 u% j; R
- protected $writeConcern;3 U$ v$ {5 l3 p3 {3 J
- protected $defaultConfig3 D* Q2 D, e! u) M4 ^* h
- = [7 I' R- f' I2 E
- 'hostname' => 'localhost',
& y/ o8 c4 ^, ~% _) P) X# A - 'port' => '27017',
9 d2 L/ G- [/ e6 w4 z# O1 j. b( h - 'username' => '',8 M. `4 f1 [9 c$ [2 O8 O5 ?
- 'password' => '',9 B7 H- i" y; v" Y& ^7 F8 I4 z% K% P) P
- 'database' => 'test'
1 u3 m$ U9 I8 G% b0 R - ];/ Q: R* n) ?9 V# }
' o: W! Z- ^9 U& o8 k- public function __construct($config) {4 p4 F0 q5 R1 o8 V. ]! k
- $config = array_merge($this->defaultConfig, $config);
5 d0 R7 ~. v, p* M; i u - $mongoServer = "mongodb://";
. X! s* M( ?/ x" i - if ($config['username']) {6 k- W( @- x4 K6 m4 v6 e8 Q" q
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
3 h: ]" T3 |: b9 E - }
0 X2 W1 b/ |, {7 K/ _( T2 Y - $mongoServer .= $config['hostname'];) s2 U9 z2 J1 q! Z
- if ($config['port']) {
; ^ J- [; |- H5 ^. ` - $mongoServer .= ':' . $config['port'];7 s" Q R- z( \, n$ \
- }: l/ ^& a/ \9 ]# r! Y' K3 P
- $mongoServer .= '/' . $config['database'];3 U* \8 p: r% S3 |
- $ z- z! m. B) M5 D/ L0 p
- $this->mongodb = new Manager($mongoServer);' z: f! A$ C% X! H3 } e
- $this->database = $config['database'];. h1 m K" p/ `$ M5 k, |0 U
- $this->collection = $config['collection'];9 \$ g2 z! C0 B4 m/ D% K5 \2 |" e
- $this->bulk = new BulkWrite();. r- b/ S. F: p8 u/ @- H$ k! H
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
+ e c7 V, `0 |) V5 I" L/ [ - }* w; m6 U! ~* A# ^4 y+ Z( A+ }' o
- 9 x4 e$ h+ n) C; @
- public function query($where = [], $option = []) {! s. M+ Q0 `3 {: }, Y
- $query = new Query($where, $option);. K! P0 ~$ y. d: ?$ A
- $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);' {- g8 ?/ [. E' v1 s M4 D* J! R; T
- & Z" p3 }; r% t) ^4 C
- return json_encode($result);
; q1 g- I( S/ B) k0 d& v - }
[; A/ B2 k$ b0 f; b - ( u) C; ^9 _, B; W5 B
- public function count($where = []) {
- X, ^ y# x- s# g! T9 M/ J, R7 ^8 M - $command = new Command(['count' => $this->collection, 'query' => $where]);
6 k5 B: O. D+ T* M& H. h6 V1 J - $result = $this->mongodb->executeCommand($this->database, $command);, {/ u+ J9 c' G2 _# }
- $res = $result->toArray();5 v# i0 N& ~3 U4 y/ K" j
- $count = 0;& f% F0 c' w; }
- if ($res) {
5 l( P3 P; T0 ^- O2 C5 g" H1 B - $count = $res[0]->n;% V9 o1 q) h% s" O# p
- }8 T( C! O% ^1 K' m" q
* a' z! e" l2 E! C5 E- a* h! g- return $count;
2 P# k2 a- _7 h+ U! B% n+ N+ } - }4 O$ c% w+ m4 S" z
: a6 g% f8 `+ j5 k5 u2 W- public function update($where = [], $update = [], $upsert = false) {
8 ^ O9 e P8 j; J* G' o& R$ a# e - $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
0 k( k2 C/ F3 i; ^4 f - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);. H0 K% H; W+ D! A' q b
, l3 \& P0 f A2 ~) n W. k- return $result->getModifiedCount();
9 U: F; d% o5 K8 M& W- [0 }) m - }( ~* S( b3 b; K
- " ^% U. B* a5 F8 A
- public function insert($data = []) {7 J: V: L, E9 c
- $this->bulk->insert($data); ~ r4 ]! \: m5 c. }& U
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
7 g: v7 ~! D) e Q! X - 1 q2 q; x5 k4 X& c
- return $result->getInsertedCount();: g9 f* E" g$ ~" y
- }
; }1 G0 w( o4 m- @: @' ~ - ( W" c9 x& G0 K' ?0 W
- public function delete($where = [], $limit = 1) {4 C- p. [. c4 Y4 [+ p9 b/ U
- $this->bulk->delete($where, ['limit' => $limit]);7 ?/ c I$ E7 F% P3 J* ^4 S7 M
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);" D: q# }/ ~- x9 v! j D
8 W; G9 y. {# a- return $result->getDeletedCount();
3 g* ^: q/ G: Y0 }3 q, A. G4 g - }
0 F4 _! U: s9 h - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原4 P9 x+ b/ V" P* h% C+ U# ^; M
2.新增- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单
! m5 Z* |( q9 V5 K. T6 F - $lastId = $resultOne->getInsertedId();
/ Z5 {" @! w/ l - $resultMany = $collention->insertMany($array, $options);//多& g( [( S% \* E% v
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [; [. j3 S3 P4 [+ T* z
- '$set' => $values
" P4 Z( e. B/ T8 c7 l3 H) M& r - ,[4 F" [. J, O, T1 d) v& N- w: x
- 'multiple' => true//多条,单条false- f* E& Z0 A% q" Q0 t/ i
- ]);
复制代码- $collection->updateOne(7 j- r* j9 U9 s c+ Z, E3 k4 y4 b5 H7 i
- ['state' => 'ny'],2 k( @- ?* k/ H0 ^
- ['$set' => ['country' => 'us']]( l- k: p, k* W
- );! }: u7 M# l( Y E( U/ t+ Y
- $updateResult = $collection->updateMany(" G! N' S+ f4 c
- ['state' => 'ny'],2 R9 B/ x0 a3 b* P
- ['$set' => ['country' => 'us']]
1 U; L7 y' g* O4 f: e - );
8 |' T. z6 ]( X - $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
# c$ k+ L% ^$ p* h6 a! t7 g9 |
- $cursor = $collection->find($condition, [9 }6 `; n, F: }
- 'name' => true//指定字段
- A/ A0 o0 E6 d; p - ]);. h% [ U7 t9 I7 p. N7 r* {2 w
- $cursor->skip(5);+ p$ M, F% ~6 {+ J) p
- $cursor->limit(5);
6 W2 z7 z% p( x" X- e' x - $cursor->sort([
9 N# z0 H0 X( B! G! h - 'time' => -1
9 X' G) X4 R+ j - ]);
复制代码- 新
9 v+ ~7 c& ~# h. J+ R% g7 n
- $cursor = $collection->find($condition, [! U6 x7 u8 c( ^
- 'skip' => 5, U0 f9 w: S2 ?+ K
- 'limit' => 5,
9 R2 N1 ?& S' m4 [# u8 L: p: ` - 'sort' => [
; P9 ^$ ` B; u4 V0 P' x - 'time' => -1
( ?2 g+ U) H0 x8 }9 r' I. r6 d - ],//排序
, @4 B$ a; |( L2 L - 'projection' => [
, A% h3 Y* @( X - 'name' => 1//指定字段6 Y& J4 n" X k, T: C1 N
- ]! i6 [4 N+ ]$ ~ x
- ]);
复制代码 5.删除- $collention->remove($condition, [- J+ B5 d& c3 A& ]$ ~
- 'justOne' => false//删单条
% _& v* l1 ?4 h - ]);
1 _9 ?, {1 o7 S* u, n( I* D - $collention->remove([]);//删所有
复制代码- 新
" q/ X* ?0 D* v$ e& j) d: N3 W. Q
- $result = $collention->deleteOne($condition, $options);
4 O2 o; q- [$ A3 O! ]9 R1 | - $collention->deleteMany($condition, $options);, X* H! F$ u* }4 b2 `
+ J8 l" V+ W- w- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([
6 p. a4 {* U3 u" X. w( K - '_id' => $tableName//我在自增表中用其它的表名作主键& b! S' g: _+ x: b4 x
- ], [
9 J2 h. ]- b5 P - '$inc' => ['id' => 1]//自增5 l- t1 G4 C% A" ~5 c* S( u4 m& C
- ], [
8 Z% \1 Q5 E- Y+ P5 S1 T5 q# _ - '_id' => 03 _$ p7 a# Z0 g) s2 X7 k: P% ]
- ], [
+ D4 V! q5 [9 p& ~8 q# h9 Z* B - 'new' => 1//返回修改后的结果,默认是修改前的4 Y* Z( @; x" \9 z
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([5 m, M% g+ `" c$ A
- '_id' => $tableName
5 f! ^$ x; G% ~2 Q; v - ], [
}% C( o# G; r j ^. y; ~2 U( P$ ~ - '$inc' => ['id' => 1]' T; }! e5 P8 g0 a
- ], [
1 O. A1 T" @1 X; A% \ - 'projection' => ['id' => 1],7 y& V) E* k5 R' V3 h2 H
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
4 c$ C2 Y0 r6 k% l; F' N9 T - ]);
复制代码 / n, U/ E% g6 `! ~" F' O b* {
' J! o) s3 [; ~6 L* \
|