使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
. Z7 I- J; Q; N/ b% m; w - s8 \1 q! z6 n/ A
- use MongoDB\Driver\Manager;
6 H9 e3 K2 f7 L5 c' Q5 j* l9 G - use MongoDB\Driver\BulkWrite;
/ h& P: X( ^* G$ L0 Z4 o$ @& K - use MongoDB\Driver\WriteConcern;9 ?, F3 Y# K- I+ i
- use MongoDB\Driver\Query;
* m8 }$ Y! U' ?0 {( ] - use MongoDB\Driver\Command;+ N+ \# U Z+ e. n
- _6 `" [4 V5 j
- class MongoDb {
: X& y" B! P9 F! U q: s4 Y
2 w) q8 B& \5 x5 r5 }- protected $mongodb;2 [7 h* n4 p+ @5 _
- protected $database;2 t6 E, s4 \4 J$ e+ y4 e9 _& ~+ k* u
- protected $collection;7 C+ n+ I9 n& @- O
- protected $bulk;1 I# _. j' u- f: `
- protected $writeConcern; B4 Q6 W. k; q- W
- protected $defaultConfig
, k: \- K L1 U" b: g- {5 a - = [
+ f, G( ?2 Y% ~8 i1 E0 R. h - 'hostname' => 'localhost',* D5 L$ C1 J1 n4 Y
- 'port' => '27017',
& Z9 A8 V+ o5 M, ^; @6 [6 y' t - 'username' => '',3 i) q X8 ? A$ P1 U
- 'password' => '',
4 j1 \" Z( H b9 c: Z - 'database' => 'test'
! @* m! r- W- n9 n2 B' ? - ];% A) W" N% E8 F8 f' A
- 1 }% n. N4 I: A8 n' h
- public function __construct($config) {
8 b; N8 j! k: Z4 U2 u U - $config = array_merge($this->defaultConfig, $config);) \% e! \! s( Z9 h6 E m$ _1 S" D
- $mongoServer = "mongodb://";2 z. Z& f! A2 U( M$ ^) c
- if ($config['username']) {& t" J$ K6 Q8 _6 `& k) M
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';5 k0 U) g6 A3 d+ ~# j: [
- }
6 x& |! G; ~/ v0 L& I - $mongoServer .= $config['hostname'];
/ D- F, P8 Y! H - if ($config['port']) {
( U5 n6 T q. e - $mongoServer .= ':' . $config['port'];
9 {8 T- B: y2 A4 ^ - }
7 _" X$ Z- t4 h4 U) j4 X1 p* o - $mongoServer .= '/' . $config['database'];
* h7 z) n# h4 N2 U: S- o
1 w5 f4 m9 y1 e: z8 d, Y/ t9 ~, S# @! N- $this->mongodb = new Manager($mongoServer);
7 V3 V9 v" g- m: _. h - $this->database = $config['database'];
5 F" X% r3 ^' `: I5 A/ D. B+ { - $this->collection = $config['collection'];
0 L; Q3 R5 Z" O+ ^/ o! ` E: n' a - $this->bulk = new BulkWrite();1 t/ y& T- r% y* x0 j3 M) ^
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);* j: |; s8 f( E0 J
- }4 _, D `0 G9 S" w
- 1 ` ~' @* [/ j0 y
- public function query($where = [], $option = []) {
+ B# j; N3 U$ b - $query = new Query($where, $option);
7 |# P1 X7 b. S8 { - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
8 d, i# P9 K* {) `1 ` - 2 u; P- P6 b8 t7 n. f1 O |
- return json_encode($result);6 a# E7 p9 f: f1 m' Y
- }/ c. _- M' b6 `
" r! P! u$ R4 J9 f- public function count($where = []) {
! u! Y$ z2 p" [3 s - $command = new Command(['count' => $this->collection, 'query' => $where]);. P" C3 w6 R% V1 K5 B9 h
- $result = $this->mongodb->executeCommand($this->database, $command);
( Y% ~6 }" ]; d8 J. t - $res = $result->toArray();0 E# c) L0 U" {. _4 a+ ]5 \/ z% D
- $count = 0;
3 H+ M7 L. B( \& M* Z* Q Q - if ($res) {
8 U: \; a/ Z5 x( ^# o- Q - $count = $res[0]->n;
" {/ h2 a: @2 L) h - }" v' @3 i. C5 a2 y8 r
1 Y5 c, I/ L! j* J4 S& q- return $count;
% p0 z0 G3 I0 u) h2 f - }5 C: D9 ]. v9 w( b7 Q
( [% c1 U) q: Y/ q* h& g- public function update($where = [], $update = [], $upsert = false) {0 V" p" u% u; i6 S+ {, r
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);- B, G6 {1 c# ~% d
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);+ P7 k( o3 j$ ^6 n4 H4 R
) k! V L2 S6 u- return $result->getModifiedCount();
4 U4 ~% w6 b( e3 {! M6 p; | M& j - }
2 m" O7 P, ^) } [' F9 f
0 Y6 ?* e5 h; i9 M1 |7 @, J- public function insert($data = []) {4 {% D, j2 y0 e( W
- $this->bulk->insert($data);/ g' e( Z7 _# b# @6 W! c- g4 S p
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);$ K6 k% M/ a6 B1 X0 }2 l! E* m% d
5 I7 s; r3 x( ]; H6 q& r- return $result->getInsertedCount();) ~' c0 I! S" V0 `
- }
X$ K }0 `7 h$ x- w - # f* O- V5 J$ T: [ _3 g/ z% m9 \! S
- public function delete($where = [], $limit = 1) {
# {2 r4 N: M* t$ x& x) ` - $this->bulk->delete($where, ['limit' => $limit]);, a' C! S4 m9 Z' T# g9 q
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
, J: j1 Y" x p3 d. u2 e7 s4 q
! f8 d2 y4 H( e- return $result->getDeletedCount();6 V8 |# E$ I1 x& [* \/ C
- }& _* a/ v! w7 ], N/ Z9 G* P0 O; T
- }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接2.新增- $collention->insert($array, $options);
复制代码- 新1 H4 R; w# C% W2 ~" {4 a& C
- $resultOne = $collention->insertOne($array, $options);//单9 x0 ]& ~' i5 @+ m' v
- $lastId = $resultOne->getInsertedId();
2 p, u* M4 Y2 C - $resultMany = $collention->insertMany($array, $options);//多3 J5 Z& N/ X. K/ K
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- 原
' T8 c7 K) h0 p' G. F3 |
- $collention->update($condition, [# R. E @; T3 J( M# B; |6 ]4 h# H. X
- '$set' => $values) l [. C, J5 q8 B* ~. D" k v$ k! H
- ,[
# D. v/ a/ I- o" `8 |( v& k - 'multiple' => true//多条,单条false
' G/ w+ ^) t: G - ]);
复制代码- $collection->updateOne(
. w# G4 t0 `7 X K - ['state' => 'ny'],
; f2 X: B7 s2 N* ?& N g - ['$set' => ['country' => 'us']]
, c7 Q9 Y$ S2 \7 \9 D - );
% R: O2 m T' Z0 g; A$ X1 ~( a - $updateResult = $collection->updateMany(7 }) e0 E* t9 ~7 t
- ['state' => 'ny']," |( |' e! W- c) n5 }5 S2 W) s# B
- ['$set' => ['country' => 'us']]
$ q9 L/ A! J9 ?. }4 @' s - );! d6 j6 I5 s- s
- $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
- D; G+ m T' b4 x& M4 T; B e
- $cursor = $collection->find($condition, [7 [* h. p) M k. }1 H/ i% N4 `, k
- 'name' => true//指定字段1 S9 e' d) i$ u
- ]);+ k4 e) _: ?* q' f. u! M/ B
- $cursor->skip(5);# r; ~) Z9 C+ }$ Q, V7 g$ T
- $cursor->limit(5);+ \$ ~( s& i9 P4 ]$ M
- $cursor->sort([" l% E/ p- F6 {/ \) k/ l; [
- 'time' => -1
7 g9 e4 A% D6 P# j% i. t0 A - ]);
复制代码- 新" F( y% Z( D3 r* G9 P% ~
- $cursor = $collection->find($condition, [! X* F) H7 X) n; }
- 'skip' => 5,7 a" |% O0 B2 {* h: r {: h8 h8 F) J
- 'limit' => 5,( t4 U( v0 [! K8 j
- 'sort' => [6 l7 s7 ~; }, [) i3 V1 y
- 'time' => -1
$ J! s5 q: ]$ X2 } c - ],//排序% g3 R5 l% c3 y
- 'projection' => [
* x* t3 }; y0 T/ @! d - 'name' => 1//指定字段
8 `9 V. H2 z* _6 T% d1 Z - ]. O( G, G! g# |0 a* {& j
- ]);
复制代码 5.删除- 原
: R5 {; U' y6 d0 f y7 }
- $collention->remove($condition, [% \/ r( b* Z( O) n* t7 r
- 'justOne' => false//删单条! k% G$ I+ i$ W/ X5 ]( P
- ]);
# w( p8 }! ^; Z# a4 j5 H! u6 X - $collention->remove([]);//删所有
复制代码- 新7 q' f" n( y. ^* l2 L8 N9 G
- $result = $collention->deleteOne($condition, $options);, p' m$ H/ X# h, b
- $collention->deleteMany($condition, $options);( f/ o+ S! k! g0 k7 E& J2 ?' R# F
- / T$ |6 |% x2 b% L" e6 c: V
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([4 D9 ^7 B; T6 Q
- '_id' => $tableName//我在自增表中用其它的表名作主键0 G. J4 m6 y- e) o
- ], [9 T* N5 F# S$ U/ q( {
- '$inc' => ['id' => 1]//自增
1 A( p7 G4 c6 ~( s2 u; C - ], [$ k3 V( S. l+ w
- '_id' => 02 ?3 f% t6 D: `0 ]5 _5 {+ m
- ], [) V) U ^- e; `" F- e( F
- 'new' => 1//返回修改后的结果,默认是修改前的9 C8 A, | e9 x. s; j
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([3 H1 ~! ^6 {7 ^4 U" I; K% ~
- '_id' => $tableName: R! F! ]- U$ ~% D; U
- ], [
4 l F6 U c2 V - '$inc' => ['id' => 1]
2 @- ^' M' ?2 k8 f+ K, `) f' @- J - ], [
. _# r6 s5 d+ t+ R - 'projection' => ['id' => 1],4 o8 P/ P. M6 o) v" D9 i) e1 O
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER8 J. I! q4 Y L" [; y
- ]);
复制代码
/ w$ x7 _0 h+ u% B; y- I L8 X/ n$ I
|