使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
! Q: `9 |* L! {8 w: x; p* F
. K& d, E; J+ {! e- use MongoDB\Driver\Manager;" u9 O2 ~! I( {7 N* x+ ?# P" Y
- use MongoDB\Driver\BulkWrite;
) b5 S* Z# s6 g, @ - use MongoDB\Driver\WriteConcern;: F- l0 d1 V4 G2 t+ x% r p
- use MongoDB\Driver\Query;4 T' ~/ r$ d1 I0 ~1 e9 [
- use MongoDB\Driver\Command;
1 Z# T1 ^- R/ ]8 A j* d
6 B% o/ M+ p9 {; K* N& T+ }$ L1 {- class MongoDb {% z- U6 }6 x- G& G# J
- / v+ g' r1 }" U$ ?2 p4 f' H
- protected $mongodb;/ W Y" R: A7 z B& y
- protected $database;& {+ F2 H) X0 D; o
- protected $collection;! a. X, [: d. w( `
- protected $bulk;
4 z% d# k- o/ H& y - protected $writeConcern;9 E. ]" t( S$ G* Z6 y5 I
- protected $defaultConfig
3 Q" `# S5 q: I - = [( J, L( i8 {/ {7 t! W8 f
- 'hostname' => 'localhost',
, t' m9 H/ u7 N7 e$ o1 _& ]; b - 'port' => '27017',0 v/ C6 Z0 D$ R2 N
- 'username' => '',
+ n6 b) P' w6 X0 f - 'password' => '',+ l* q/ B+ O. A
- 'database' => 'test'
: N: S/ J, N9 d4 s& E1 @8 E - ];$ l( t/ P Q" l8 U3 v8 S1 M. s
- + j$ k) i1 F0 U2 ]3 Z8 H; D
- public function __construct($config) {
/ a, w* v# Z! v0 m - $config = array_merge($this->defaultConfig, $config);
! m: C8 o: L, C1 r9 z5 i0 Y - $mongoServer = "mongodb://";0 @2 |, ` H1 Y6 B2 {+ R/ R
- if ($config['username']) {0 f7 i! t; E+ v( d H |
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
. F+ D: O( ]! _! E4 Q( u - }
. s4 V+ M' ]" A% z - $mongoServer .= $config['hostname'];3 P( @2 l" U( q, D0 \
- if ($config['port']) {
; @- {$ `- @( j# R c - $mongoServer .= ':' . $config['port'];7 j: h7 T) ?6 X, j
- }
- h4 ]' B# _& U+ c - $mongoServer .= '/' . $config['database'];* C( Z# E- ?8 ]1 \# ]
- * M( u6 B# f8 _2 h
- $this->mongodb = new Manager($mongoServer);
% c8 i0 K( h7 s2 D, _ - $this->database = $config['database']; N- W6 r' J9 H) w
- $this->collection = $config['collection'];
' A o* J( W$ \8 E1 c0 K+ J2 m - $this->bulk = new BulkWrite();; G& K4 M! B" C, g5 x, {2 A
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);* X: R/ |! _$ b
- }
5 M2 k$ u, w \* w2 t
5 Y; f1 Y; [* X6 E2 j6 B- public function query($where = [], $option = []) {7 D6 z8 W0 _7 h& a
- $query = new Query($where, $option);' n: Y3 @; J; E. v+ b0 I8 U
- $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);7 G, H$ ]4 p' e, C0 L) G( \
- ; U9 @7 q7 Z, k
- return json_encode($result);
: o( w$ X+ N0 J6 r; i0 i - }7 a! }! A! Y2 x1 U
- + \, X: t- r- w2 n: i; w A) ~& I
- public function count($where = []) {, ^; J5 Y. v0 I& j
- $command = new Command(['count' => $this->collection, 'query' => $where]);
1 b- W" [' m) _1 b+ V - $result = $this->mongodb->executeCommand($this->database, $command);
/ z3 f& y3 Z. x; a9 x" g; o9 ? - $res = $result->toArray();2 Z: O1 R7 j- J6 R9 z* k
- $count = 0;* [" v' ~: z( v( z, w& A& H
- if ($res) {8 l, U4 P3 h- v7 J
- $count = $res[0]->n;# @& @ C3 o# Z _' P3 m
- }
+ m' }5 F0 b/ p9 B - ' y/ }: s1 V7 C/ l
- return $count;
3 T* V2 E' l }! O7 F - }. R/ g7 n5 Z. s% a+ q. r' S' {+ E
1 P. O/ F: f8 j/ e- public function update($where = [], $update = [], $upsert = false) {
7 o3 y1 b+ |2 \( d& L - $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);$ e' y+ I1 ^, p2 a+ Y. E
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
! d: x0 L6 B, s" @+ x# x& i - 6 j' {. }- j% R$ H; ^7 m
- return $result->getModifiedCount();
2 P. Z- i$ \4 u9 ^ - }
" ^9 F! C! q! ?3 \8 ?& x# s, ~ - I3 C4 w8 Y' n+ r4 Z( n
- public function insert($data = []) {
5 Q' g# x/ d$ P0 H1 S - $this->bulk->insert($data);! Y8 y1 l3 ], F0 C) u
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
+ G8 k8 Y! ^3 Y- x - & p- t6 v# Y/ x/ c$ n+ i
- return $result->getInsertedCount();
# y% X6 T- Z0 {# O' q3 m) ]2 I" Z! k5 j - }
: } ~% m' W- V3 e1 r3 q
0 M, K/ N b- B) V- public function delete($where = [], $limit = 1) {% J, I" D$ z6 Z! D6 x
- $this->bulk->delete($where, ['limit' => $limit]);- J! j, B0 V8 b0 P- e
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);0 u7 V x0 O% V0 e5 n4 M6 a0 {
- 4 d2 t8 u6 t, V( @6 ^; K
- return $result->getDeletedCount();: ]: m z; E% H' ?+ |' d) g7 m
- }
6 ~% ~5 }7 d% E# _" z - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接2.新增- 原
, z. P$ x* }' V& A6 B9 K7 h" V' m
- $collention->insert($array, $options);
复制代码- 新
4 v4 Y# r6 Y) r1 Q; y% Y
- $resultOne = $collention->insertOne($array, $options);//单
) p+ ]4 O: s' h - $lastId = $resultOne->getInsertedId();
6 C' F5 E4 \, Z' S( x1 t; y - $resultMany = $collention->insertMany($array, $options);//多) E4 i: Z; `1 g# y4 E, \
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [' U' [; S/ O) y# c9 V5 l3 B8 k2 f
- '$set' => $values
% c6 {, N6 D! ]' D/ k, A# ^1 o - ,[0 [" g: u, F8 Y& h. e$ j
- 'multiple' => true//多条,单条false
* J, b1 c, H( E' z _ - ]);
复制代码- 新
9 p$ g; H: F& a# D1 `8 A
- $collection->updateOne(
# j: V$ A. m' G" m: H" A' J - ['state' => 'ny'],
! \) @, G- U8 h% A; t) y+ C& ? - ['$set' => ['country' => 'us']]. d1 I6 M. ^5 j# N& }5 {
- );+ y' _. A, t' g0 U" X2 I6 }$ W
- $updateResult = $collection->updateMany(
. m. W% _+ c9 J1 X ~8 C l" r - ['state' => 'ny'],! }) l8 b0 @) f1 p8 [
- ['$set' => ['country' => 'us']]
( n$ U6 k( H2 A5 t0 } - );
6 b2 P5 {3 R1 `$ P+ y- D" q0 e/ P1 e) } - $count = $updateResult->getModifiedCount();
复制代码 4.查询- $cursor = $collection->find($condition, [
+ @! m! U2 \$ G3 n. R - 'name' => true//指定字段1 ~: Q1 V3 n( s
- ]);
8 \ Z; V& ?/ _6 w& A - $cursor->skip(5);
, U5 _( P e( A3 D) p9 v, O5 \0 { - $cursor->limit(5);
, ^8 h# [2 l- ], T5 i - $cursor->sort([
9 B8 h, n: M( \9 ~6 T - 'time' => -1 k3 t: q, [8 _1 J0 y
- ]);
复制代码- $cursor = $collection->find($condition, [+ B' P# c! B: ?
- 'skip' => 5,* S3 Z+ n. [1 R# i
- 'limit' => 5,) V1 q& {% }2 V* ~, r5 k
- 'sort' => [4 U M6 g+ I9 G9 G; h
- 'time' => -1
3 X/ C2 g0 T; j8 ^. [4 v - ],//排序
. n$ {# j% H+ W h5 i - 'projection' => [
7 M2 n6 G) G C9 N8 \/ M& { - 'name' => 1//指定字段6 a {% I s9 U
- ]
2 s$ H7 V8 U0 G0 t( _ - ]);
复制代码 5.删除- 原
; ]4 X- s7 e2 a3 N3 x8 d! L
- $collention->remove($condition, [' a' M. y9 r& O' c7 {
- 'justOne' => false//删单条
6 _$ ~1 S# j7 Z4 A, i! g# D8 x - ]);4 l" A7 X: F8 C/ V
- $collention->remove([]);//删所有
复制代码- 新! m! h: E: g' I! L- x+ }
- $result = $collention->deleteOne($condition, $options); q. w7 s+ a6 z# n" d7 T7 A: X' p, @
- $collention->deleteMany($condition, $options);
7 h8 B7 @/ Q9 } - 1 z$ E5 D2 ^2 u$ a
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([
4 O" ]7 [0 B0 F5 f% |* k" u% b; T - '_id' => $tableName//我在自增表中用其它的表名作主键0 Z/ a1 } U6 y4 Y
- ], [ r; }9 N, ]6 H3 y0 Y
- '$inc' => ['id' => 1]//自增
7 ^4 I/ {! }/ d% } G) P/ ?0 \* m0 q - ], [
C- J5 @+ a1 w# ~2 |7 `0 ~6 p' Y# H - '_id' => 0, S0 j0 f( F% I
- ], [
8 y2 K1 @, {9 L) q7 \% ? - 'new' => 1//返回修改后的结果,默认是修改前的 N9 @1 c% B" e1 o
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([& W* F" G3 ?/ X/ `8 p$ x5 L
- '_id' => $tableName
1 x2 S5 O, r0 ~! V - ], [: ]' ?: U, A6 q
- '$inc' => ['id' => 1]2 o2 {8 R5 \/ b1 K: {' a* P
- ], [1 _, M) Y3 N( o* y4 `) [" A+ x
- 'projection' => ['id' => 1],
3 c3 i! S+ C% c- ^5 e/ n7 `% Y - 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
, o' t4 ?+ Q8 F' K4 L4 c E' h ^ - ]);
复制代码 * V4 Q+ a2 ^, L0 P1 d+ ~
7 v( T( q5 g1 q |