|
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
: `; `. h/ t; j2 N7 s! ?) @0 @ - , P" `2 A) Y. M# c0 t
- use MongoDB\Driver\Manager;
' z/ |5 E; H+ @/ T9 j5 i1 w+ S - use MongoDB\Driver\BulkWrite;& l7 ]9 e& E5 @/ d
- use MongoDB\Driver\WriteConcern;
$ I+ r% o7 J, Q$ M, u) `& x - use MongoDB\Driver\Query;
4 D& J3 {) M+ }% `# Q- U - use MongoDB\Driver\Command;# [3 T5 M2 d4 R/ }- S
- & E6 S: B' r, @% q) G7 J- ^
- class MongoDb {0 B; R' t8 _5 B( e. q
- 7 o u* _+ r3 t# n$ @6 v1 N' v" }
- protected $mongodb;9 D9 _, h/ o Y8 Q
- protected $database;
2 R- _7 D4 p( f8 R7 o) {- E4 J - protected $collection;
: h; X* ^" `) |5 q - protected $bulk;. T5 T4 R8 H3 e* r6 y; @
- protected $writeConcern;
/ e8 O( X! Y1 d3 W* U, J, E - protected $defaultConfig
% y: I; i9 p: t( o7 ` - = [0 X; t. ^+ g7 I, B, F0 l% I
- 'hostname' => 'localhost',
V; P4 I M0 f* A" y: T - 'port' => '27017',# l% P5 T+ F. h3 S# y$ L7 h' h4 f, d
- 'username' => '',1 W# `% q6 i5 S2 }/ d! F P
- 'password' => '',
- c4 \# r8 a% Q - 'database' => 'test'+ j7 | ^9 O; q) M1 r
- ];9 c: V# _) `9 b
- p9 k+ }! E T3 [3 b
- public function __construct($config) {
; w/ [. }, r9 [/ I4 K f - $config = array_merge($this->defaultConfig, $config);, C/ `' Q+ u; l- m$ O4 [3 r: T
- $mongoServer = "mongodb://";
$ W& _. B* }3 m- w: q: P7 D' R - if ($config['username']) {
{; i! ~3 n- W. o/ X, ?" Y - $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
) [* ~, z/ Y) i% H4 c$ D - }4 O' S& \2 E) I7 B* s* L( d
- $mongoServer .= $config['hostname'];4 \) `0 p/ C5 ]2 A8 K1 t
- if ($config['port']) {0 G" M9 Z c% ~6 N
- $mongoServer .= ':' . $config['port'];
6 D6 @! Z, m$ \8 y& C+ `5 V# c - }) z/ e' ?; ~# P$ F0 @+ V
- $mongoServer .= '/' . $config['database'];
* x; P* \- e8 G. R* I - ' f) l# L4 f4 Z; Q2 @# J# F) C2 t
- $this->mongodb = new Manager($mongoServer);
6 z* a) ]) \ h! y; G, n- E - $this->database = $config['database'];
- f5 H5 R V+ E' z0 V - $this->collection = $config['collection'];1 U% Z K) i( U
- $this->bulk = new BulkWrite();
: A0 ~) V* X; M4 V" G- Z/ { - $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
& b1 B( V' t8 L; X4 L - }$ w) |, {' V/ |9 }0 D6 l8 K
- ' U3 q" H# q% I2 `: @; T
- public function query($where = [], $option = []) {
: j) u3 i$ K- [: R - $query = new Query($where, $option);
, a2 b+ @* w$ w8 J, d; P - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);: m+ {- B, z# b7 ^( A- z( T' E
- 0 g* t0 j. Q# U2 l
- return json_encode($result);
" ~. s0 z( t7 c2 B: ` - }2 J9 |9 S; F" h" s' W
U$ |5 v* l/ d# g- public function count($where = []) {- G9 J6 c. m2 u' A. |1 P. y% I
- $command = new Command(['count' => $this->collection, 'query' => $where]);9 }: V% d$ X- Q* b
- $result = $this->mongodb->executeCommand($this->database, $command);0 I- P' o5 {1 Y6 O) f! B- a
- $res = $result->toArray();" T* o, H" @, I0 g
- $count = 0;
+ n$ j: a7 I( m& _ - if ($res) {
& F, x9 V# z* D! q1 E0 I1 ` - $count = $res[0]->n;
% b; E" Y/ k! j- L$ r - }: |& Y& n# t+ O8 x( I
- 7 O* z/ t/ P l* W1 c/ D
- return $count;; W. Z/ z( b4 s1 I' [) u
- }
: p& |6 B* G7 Y/ V
$ Y% a" B6 {9 j& ~( ?- public function update($where = [], $update = [], $upsert = false) {
( m9 j$ z r; i - $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
1 C$ Q3 l& q: x - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
- k- M3 K% e' h- L% ^: g - % f5 ?- R, O, @
- return $result->getModifiedCount();4 O4 Q' ]/ P; M* o" i j
- }
8 ]- F S# K x! N& u/ }: I1 o - " D5 C a' G( N( f* H- d
- public function insert($data = []) {
6 Z6 J' d1 C0 ]* N' r) i4 I/ E - $this->bulk->insert($data);$ u+ _* C! s8 Q* C" Y5 ~
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
5 }% u$ V) j& Z; I5 F# d9 c; l - 5 H+ U" ~0 R1 t
- return $result->getInsertedCount();! b% z$ U9 m- x
- }
' L1 n' ~0 ?3 } s
+ u& q q. ^( M6 s- a9 g- public function delete($where = [], $limit = 1) {4 A0 M2 E1 S+ l
- $this->bulk->delete($where, ['limit' => $limit]);
+ t! C5 ^4 Z, o+ l - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
. J. ^ |% u# R- O - 7 v" G4 Q( J3 z; F; U n% ]: i9 a
- return $result->getDeletedCount();: D' C; T; M" ~9 T$ G
- }
9 M) B+ A, S1 I8 ` - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原
* Y; ?7 G4 ~5 v7 i' {' u
- 新
: H W* ]/ W0 p0 n0 m5 U- a; J 2.新增- 原7 I9 u) i* w6 \$ o0 G& y2 c6 U
- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单
7 }% F1 e+ O% H; ~8 P' D( p - $lastId = $resultOne->getInsertedId();
$ N6 `7 C$ X1 A, E8 k1 p/ i+ A# o - $resultMany = $collention->insertMany($array, $options);//多; F' J+ u0 b( b* H Q& z
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [
% H4 L! S0 J$ T7 } - '$set' => $values# U4 K2 ]( j. |9 ?2 J, _! [
- ,[
2 w. t7 H! Z2 e: a; Y$ Q - 'multiple' => true//多条,单条false5 ^, |9 U' \; D' J5 X" Z+ T4 H
- ]);
复制代码- $collection->updateOne(
- L: I0 ^# s2 } P5 F4 L - ['state' => 'ny'],2 D T, D$ ~- o" ]% H
- ['$set' => ['country' => 'us']]
7 u6 r3 r1 c$ R4 ~- W - );% J( E5 q D& m
- $updateResult = $collection->updateMany(
. R4 {0 Y1 u. R# X W/ e+ U - ['state' => 'ny'],6 m" r. `, P/ u) |5 e
- ['$set' => ['country' => 'us']]
7 d5 w. Y" @% b8 |' p% B - );
) i/ d! ?( v. D( W! U - $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原( I3 n5 ~1 O$ d m C/ U+ G1 Q' m9 F
- $cursor = $collection->find($condition, [4 \, {% k- C! C# u0 @$ I
- 'name' => true//指定字段" ~5 m' X8 }5 p2 N2 R2 w
- ]);
3 u5 p# Z) [9 { p" r5 | - $cursor->skip(5);
" W0 f5 O" r) } - $cursor->limit(5);8 O. Q4 b5 B; {, Y
- $cursor->sort([2 V& u/ I% B1 A$ V# H3 F
- 'time' => -1" m) w) i& E2 D8 ?- ^$ X5 O
- ]);
复制代码- 新2 P/ O4 C, X0 a, F0 Y1 \
- $cursor = $collection->find($condition, [
' E1 \9 V1 v: R# r: { - 'skip' => 5,
l, ?; C* Q+ R- K3 F7 T: H% o - 'limit' => 5,
$ k4 u4 E" i0 V9 [9 P - 'sort' => [
0 s2 e6 ^. ?6 C - 'time' => -1) N2 R$ c& i% O: e
- ],//排序- n+ I2 t1 Z- T V ~3 g% T3 G
- 'projection' => [6 M+ s8 G. ~% _0 [( g
- 'name' => 1//指定字段4 T/ U: O8 b( c' R" [
- ]
0 }. x* k$ q: f7 m" }0 Z w) E - ]);
复制代码 5.删除- 原: K2 V' q( O! T4 j* m% q
- $collention->remove($condition, [3 |! t. F8 Y& a) N
- 'justOne' => false//删单条; q8 i2 y* q& d0 Y
- ]);
' R! I5 V. W E5 Q) I1 X. @ - $collention->remove([]);//删所有
复制代码- 新3 A/ S0 p3 G' r% L5 \; i/ G
- $result = $collention->deleteOne($condition, $options);8 J2 z" M H; b. ]
- $collention->deleteMany($condition, $options);- ]' [1 ~# K. `( D9 `- t! d
- 3 L3 `) u! C8 X) u
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([3 {5 J! W+ R. t( {- v
- '_id' => $tableName//我在自增表中用其它的表名作主键
5 Z; e# D. g7 b - ], [- y% w- S9 A: K- H
- '$inc' => ['id' => 1]//自增
! k* S1 Y( Q, R. c3 D! g" y - ], [5 n- y$ N' {3 I, } Q) h1 l7 i1 e
- '_id' => 0
- i' }4 M) n' y/ {! O+ ~5 O - ], [" ~$ |8 W3 X; f5 g. E
- 'new' => 1//返回修改后的结果,默认是修改前的' T/ ]9 Q+ E5 N' P
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([0 m, t6 Y" R# |5 s
- '_id' => $tableName
8 q) F! h k/ V6 S) r - ], [' C! U; X6 a# }
- '$inc' => ['id' => 1]* n- G- n. _% ]. g# x# X
- ], [
) n, T: ^* t& a, L1 s0 e - 'projection' => ['id' => 1],
6 S8 V# n! T0 Z2 J - 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
& L5 h+ Y+ R. w7 C7 x, ] - ]);
复制代码 # Z4 R2 f' W8 Y* r% n+ W
4 s }% ]- T0 d2 K# C' k$ O |