使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
6 e% `* Q' M. g0 B9 W) S+ H
9 Y7 W: ^' P0 m- use MongoDB\Driver\Manager;/ Y; q7 D% X* H4 t' e* G' B4 l2 R
- use MongoDB\Driver\BulkWrite;
% N. j4 c+ z+ m3 y" M6 ] - use MongoDB\Driver\WriteConcern;
$ k. Z7 ^1 ` k( U; ^ - use MongoDB\Driver\Query;
# d4 f u! m, t* q6 ]- k$ d - use MongoDB\Driver\Command;
- W: b3 q3 {2 Q2 L; q0 k - 6 F! t8 y/ ~8 }% a- _0 Y& [
- class MongoDb {
3 W( s- y1 K4 x! f( R - # N& V, x% q8 i. P' r; c' U
- protected $mongodb;
: n, W Q/ [) z+ b7 _ - protected $database;7 V4 r: ~3 z+ U2 {( t5 {4 A R
- protected $collection;
0 [7 o0 {) Y& L. U! e0 u6 L* X - protected $bulk;
% H; Z v/ o, G) P6 U* F2 B+ p - protected $writeConcern;# T# ^6 A' [" V- p0 N& B7 r6 D
- protected $defaultConfig
( ~ i& D2 M7 I* m7 a - = [
7 {7 v8 }4 l2 W( y$ }$ u: ], Z4 u - 'hostname' => 'localhost',
8 x- q4 a7 J3 b7 h! Q0 ~4 t - 'port' => '27017',# U; C9 Z4 t* I$ G0 n
- 'username' => '',
. |4 j% m6 v- V: [ | - 'password' => '',9 ]: t. c8 e Z6 T
- 'database' => 'test'& e$ c3 j- l& _* b
- ];( \/ \2 v, _/ N1 c' `/ C" E
6 Q( r$ q7 E6 i; g- public function __construct($config) {$ ~" `2 _3 J! \5 i) b4 e8 O
- $config = array_merge($this->defaultConfig, $config);
- a9 r3 x$ n! i; b3 ^1 R+ W; D, b - $mongoServer = "mongodb://";) F6 Z2 i& \: [5 z9 ]
- if ($config['username']) {
! o$ S8 O2 A# P5 _7 n - $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
2 m9 D2 g' z6 R) \ C7 y' K - }" J( Y- _" o; Q
- $mongoServer .= $config['hostname'];
6 |9 f1 n6 d* z( B# { - if ($config['port']) {
* z6 S/ @" ?1 }9 U5 ?- G: r# e' Y - $mongoServer .= ':' . $config['port'];
( O8 n9 \" s0 j7 a6 v& D4 z3 @6 ~, n - }
& M, D- {; G* S' G, @' r - $mongoServer .= '/' . $config['database'];) a; r& y1 D, V1 F
- M( {& F, {) B" W- $this->mongodb = new Manager($mongoServer);
5 [' J# k. s- \2 \. i2 h - $this->database = $config['database'];+ X# [5 C" b. p# R% N3 d7 U8 V3 v
- $this->collection = $config['collection'];
% f" _% X: t3 `: o; v; ^- f+ U2 I - $this->bulk = new BulkWrite();: n- i p8 \4 J2 M
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
' C2 F& J/ I0 D2 H - }
* ^* @% _& e4 b% Q4 C - - t" L. f7 b" \9 A6 C3 \; a; _! I- k
- public function query($where = [], $option = []) {" m0 ]/ [7 S. z- F: Y+ P3 }4 |
- $query = new Query($where, $option);
3 j" x. i6 T. h9 A9 S' { - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);# Y; l8 G, ~/ ~' P U
; N, M7 X. e* t. M' w, G- return json_encode($result);7 o a, ^+ B- Q# V7 g8 v
- }/ I& T4 m" S1 L6 S
- / ~/ X* o# T* \, m
- public function count($where = []) {
. s1 S/ m6 J- w6 x1 R - $command = new Command(['count' => $this->collection, 'query' => $where]);6 {+ X6 u) \) }) Y% r
- $result = $this->mongodb->executeCommand($this->database, $command);* |% r' F; \. l/ @3 e
- $res = $result->toArray();
) m8 Y7 {, E: t: ^8 T - $count = 0;+ O; T/ G7 E& v
- if ($res) {1 w5 k# a6 l8 c/ a1 S+ }. v
- $count = $res[0]->n;
% g# t5 k" g* v3 l- T" M) W, O - }
4 \# f/ i! ]. m4 c7 b# a
0 e( d1 p* D/ B0 f8 m6 {- return $count;
7 i$ s3 q4 w, c - }
2 o+ k' k% {9 [3 h- q( x1 \ - u; C E& ]. I1 k9 J. [
- public function update($where = [], $update = [], $upsert = false) {% G) \, @# l/ r8 }; L! e& M* ~
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);7 m, f. t f# X+ t
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);; |* T& N) F% h: J3 }1 {
# ~( D/ m& K' a* y5 A- return $result->getModifiedCount();
~: {* z# }0 t9 A - }
+ f6 n/ F7 _# Q3 G: m" U" B4 Z( X& P - . [& `* }" k) y( V7 [. o( [2 D
- public function insert($data = []) {
) Q! Y# S6 H7 t/ y - $this->bulk->insert($data);
; d0 I. y f0 t - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);9 e! \, K# I) d: K; Q" Q4 H
- / ~" _2 y$ X% I* v1 i ~0 n
- return $result->getInsertedCount();+ Q: `! h, M) }. ^
- }2 O1 A+ E* Q. r# n/ a* R" ?
- 2 \6 h* M; f; J- K8 j; G; O; `4 o
- public function delete($where = [], $limit = 1) {! [/ l- P& X! h
- $this->bulk->delete($where, ['limit' => $limit]);
+ V+ m& s$ `% E Q/ \) c K - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);2 n2 c% K' z' d$ R G
- + Q( i: C1 Z6 b7 ?0 u
- return $result->getDeletedCount();
# F4 _0 [/ y \ - }
% v: r9 C v }1 Y) X8 [ - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 新
6 S8 R4 l5 Y+ q$ o# e1 U) k+ z 2.新增- 原# R: z% Z1 B6 S/ z1 x8 m9 a
- $collention->insert($array, $options);
复制代码- 新1 r4 Z8 B6 q' Y$ u4 a1 r! q
- $resultOne = $collention->insertOne($array, $options);//单% g* a% w& Z2 Y8 Y4 h
- $lastId = $resultOne->getInsertedId();7 W" ~. |8 i2 w3 p4 w- @/ H
- $resultMany = $collention->insertMany($array, $options);//多
9 s; @2 L9 s' i - $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [5 G t" p; ]- `' O8 ?1 I1 ^6 p% |7 T
- '$set' => $values7 X4 T/ ?( } P8 \" l
- ,[6 P0 ^% {& z7 J8 X D, G4 m+ f1 [
- 'multiple' => true//多条,单条false2 h: r, ]4 p$ r4 {3 K5 L/ i7 B
- ]);
复制代码- $collection->updateOne(7 u' c9 w& z* S/ U4 Z
- ['state' => 'ny'],
9 n! Y6 D1 e, Y5 ^2 g - ['$set' => ['country' => 'us']]1 ~/ x: |1 c a
- );( i& I( {0 x, U" O5 H3 S4 ?4 W. d
- $updateResult = $collection->updateMany() M) c$ q* q# Q6 x
- ['state' => 'ny'],
$ z2 A$ M S. ~, k- O+ O - ['$set' => ['country' => 'us']]: n0 w# }3 F5 u2 t# C
- );$ C5 y* b# q1 K
- $count = $updateResult->getModifiedCount();
复制代码 4.查询- $cursor = $collection->find($condition, [
) x, h! {4 k! |& |" U8 c. ^. b - 'name' => true//指定字段- l: {+ y( h( F& m5 I- b0 Q
- ]);1 g( p3 N' O8 O: h5 n- u
- $cursor->skip(5);" P6 r/ X! U8 @ _! ]! P
- $cursor->limit(5);/ G$ V4 T8 q! X+ r/ n; w* h
- $cursor->sort([
! n- f* U, [: ~; n) P( P - 'time' => -1
: Z$ u$ @+ _: \+ D @( ?* I - ]);
复制代码- $cursor = $collection->find($condition, [
) E: B4 \- _% _1 ?0 M1 n - 'skip' => 5,
3 N5 t% d5 M1 S( w - 'limit' => 5,
1 V- T- ^) H1 c! x7 _ - 'sort' => [
: c6 S8 I4 b. V9 z, f+ B6 n' H: A" l - 'time' => -1 v+ }9 y$ W& n1 V o9 h* x
- ],//排序- S0 {9 J, C2 N$ ]3 R n6 a; [
- 'projection' => [
7 Y' I( E5 L E& U5 A) Z - 'name' => 1//指定字段; T0 Q" y: l) y1 d# {
- ]" O% f+ J$ {4 o& s# y" M) _$ @- L6 D/ W
- ]);
复制代码 5.删除- 原; q4 J' J/ |4 ^2 A$ s. I# O% K
- $collention->remove($condition, [# Z+ e/ S$ t6 ~% Z0 o- [* `0 y& x
- 'justOne' => false//删单条% g. E6 D5 O$ x& b B9 u
- ]);
" H3 w& q' P; G [7 K: {( M - $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);
% p- k4 f, |$ a' U5 x0 V - $collention->deleteMany($condition, $options);+ m" j( g# c% U: ? U4 }7 Y5 s9 v! V
- * c- l. }$ _; S, t) \# }1 }+ s
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([9 P' W1 r; P* ^ J) ?; m
- '_id' => $tableName//我在自增表中用其它的表名作主键" T$ a1 F$ z+ q- P0 F
- ], [
9 |" O/ P1 B; z; g1 q+ k - '$inc' => ['id' => 1]//自增+ b' f4 ?3 r5 E7 ]% Q: u- J T' l
- ], [
+ ^8 H: g+ B/ W& z9 l. E - '_id' => 0
. ]) @2 b! A6 | O# m# z& R4 _ - ], [
' I) S n6 Y$ I6 r. v - 'new' => 1//返回修改后的结果,默认是修改前的
/ @5 p3 a) [. f( i |9 |$ q - ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([
* e# Q4 D! g J! n+ s - '_id' => $tableName
$ ^" S- g3 f; h) b4 c2 ]: f/ `1 k - ], [
+ T: s6 E) b: B8 ~+ V3 f - '$inc' => ['id' => 1]. O5 `4 U( t0 |, b; G2 a' O
- ], [3 R/ c9 O4 K1 e2 q; ^# [
- 'projection' => ['id' => 1],
" c! i' k! A9 {, Q; @5 r - 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
" j0 M& E' E/ E% p5 Y - ]);
复制代码 * K( a; e1 q3 r. U( A* s
& F( @; j& F- J- ^* W7 S. _
|