|
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
" L5 x8 h* N: c
5 v9 U- l, {# B$ E" O( b' |4 `9 v, X+ O- use MongoDB\Driver\Manager;
3 N# C% F; j$ P2 b' R r - use MongoDB\Driver\BulkWrite;
( i! N# |7 X5 i. n7 T, N3 A - use MongoDB\Driver\WriteConcern;
K C0 D$ ]# m; _; |* P% X' [ - use MongoDB\Driver\Query;
, Z9 @& F. j' N. j9 l. a+ V - use MongoDB\Driver\Command;2 j! ~1 k9 w9 L' P
0 Z# f2 [8 l" H+ k- class MongoDb {
( ]7 l. N/ y6 U/ j
# W( Y) d/ W. O8 ]' j" [- protected $mongodb;
) S. _5 T6 Q( m1 h) L Q$ @ - protected $database;! Y+ D4 W# m: v# ~# f. n
- protected $collection;/ {5 Q# D0 Q+ w+ u Q6 ^" K
- protected $bulk;) p4 W. B, m& O* @+ H# o% @
- protected $writeConcern;* }" H! f" [& y: v7 q/ e5 O, \
- protected $defaultConfig
6 V" \, i2 h: V- i" S0 P - = [5 V' e3 s8 V f
- 'hostname' => 'localhost',
( }! {# `& X" g+ s - 'port' => '27017',+ S/ f# f# i! H" s
- 'username' => '',' z$ J5 W4 Z7 U2 _$ q
- 'password' => '',2 L# }7 Y0 p0 _! l, t
- 'database' => 'test'
* D9 X* ~, V3 F$ B - ];+ C* d/ K6 Y( K- M/ w
4 O% p' ?+ O4 ?- public function __construct($config) {
5 v! w3 ^9 k) B' l - $config = array_merge($this->defaultConfig, $config);+ z( H% Q8 T4 q6 N
- $mongoServer = "mongodb://";) [/ K! f& Y& E3 G7 V* {
- if ($config['username']) {$ N* K% G$ {: H, D# s" Q4 C
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';, W+ A, a* Z6 t9 S6 b4 d
- }
" \7 `: F) C- S$ u8 _ - $mongoServer .= $config['hostname'];* I& q8 Q0 {6 A" C7 c2 ]: Z
- if ($config['port']) {; J- y! f, q, w/ C
- $mongoServer .= ':' . $config['port'];6 n7 _- @- ?9 }
- }' i* t) E- _2 p/ A5 x
- $mongoServer .= '/' . $config['database'];
2 U3 ]- k; o u" K# w6 x5 N9 n6 p
2 _: e+ I2 N0 Z; \, S- $this->mongodb = new Manager($mongoServer);
* Q1 w) v# }; t. I) s - $this->database = $config['database'];2 t5 x3 `) `4 ~' J) y s' t1 h& }6 @$ b
- $this->collection = $config['collection'];4 ?: G9 _3 o; l/ S, F; x& s i
- $this->bulk = new BulkWrite();+ B$ A3 `. Y6 m) g5 h$ N8 {( F# B
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
5 i Z* K0 s" B. a7 t - }& N& Z1 I' e. w$ P
- ; e; w( m. w, r) }5 d
- public function query($where = [], $option = []) {
) X! q5 Z+ g$ N8 \2 y - $query = new Query($where, $option);
6 g0 e+ |; j- N' k+ t* N$ R9 `; ~ - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);7 B- N- K3 g/ a+ w, w& A
- ( v4 S* n; m/ _3 a0 x
- return json_encode($result);7 S+ u$ ?. B9 i0 Z$ z
- }
# `1 z, s5 Z0 P - ! L* l/ y% W% X/ n" O; H; F
- public function count($where = []) {
U' w/ ^2 r Y) M - $command = new Command(['count' => $this->collection, 'query' => $where]);
& A1 a- {, |4 j - $result = $this->mongodb->executeCommand($this->database, $command);
7 T! X5 F! q) W1 I7 } f& |; Z7 q - $res = $result->toArray();
1 d- J4 J0 V4 a7 v/ H, ` - $count = 0;$ i4 Z3 D5 {+ y
- if ($res) {
7 a h& I# [& |. p1 \ - $count = $res[0]->n;
( N& N( K, A" [- ?* [1 S+ {- Y - }! |- z: q! R4 z0 u, z7 f
7 Z2 r, N) ^7 o# u! |- return $count;
6 l- a5 `$ M/ p& \5 K. } - }1 j4 t" _ y! h% J$ l' \
- # W6 L2 o- n( A( P6 w
- public function update($where = [], $update = [], $upsert = false) {
0 }6 T& d2 T1 s - $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);7 Q: j, Z& I l9 k
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);3 e9 O% `9 S+ e, H( I
8 f1 Y; r% Q5 `9 j) J9 z! r- return $result->getModifiedCount();
( A( ^$ ~( M8 C3 B7 S - }
: q6 Z+ q6 I% i, }% A2 n, s1 O% K
4 k# w3 Z9 Z5 A$ ^% G. @ _- public function insert($data = []) {
% w: ~0 F; o% g% G - $this->bulk->insert($data);* }" Q$ V$ ?: E! \1 R
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
6 M" B2 u2 a( n& E# I x' a1 h
+ I4 T$ W; U8 U- return $result->getInsertedCount();$ \! F7 P. ]6 B0 I8 u9 ~+ K7 `
- }
. [; ?' b4 ]; j
( V1 q& H$ @ S- public function delete($where = [], $limit = 1) {
8 o9 X4 R4 _' k1 X' a - $this->bulk->delete($where, ['limit' => $limit]);8 E% j( C! P' f$ ~
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);2 {2 [# M: C, K7 V) J. a7 d
7 F* L( Z' l2 a# I; d0 s5 o- return $result->getDeletedCount();
, @! `% A4 V$ f9 r - }
( u2 B/ f; t+ u5 z( i - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 新
# U8 c; q7 p6 A1 h" Z5 Q5 I 2.新增- 原3 _8 Z3 k' z6 U) [2 j# g) V4 J
- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单+ j9 U# W1 l7 ~4 K- V& p! X( F
- $lastId = $resultOne->getInsertedId();
/ _ i& Y! R1 N& {$ ]) m - $resultMany = $collention->insertMany($array, $options);//多
0 ^# w9 n& ]+ i6 | - $count = $resultMany->getInsertedCount();
复制代码 3.修改- 原
% {; P, c# h' B) S3 A% D
- $collention->update($condition, [. ^+ k! @# Y5 `( l/ k6 z
- '$set' => $values/ h Z! ], m) L4 ]
- ,[
5 a" o$ i# i. f1 F - 'multiple' => true//多条,单条false4 ]+ U3 C, h. k- F
- ]);
复制代码- 新
2 z3 e4 g+ N, `$ m' n1 J4 W
- $collection->updateOne(" K* `6 f! s9 O4 k/ W$ a
- ['state' => 'ny'],, y% ?% Z& {# N. U0 _/ D3 D
- ['$set' => ['country' => 'us']]( a9 B3 u0 n j! G
- );# V Z/ n) A1 Q, j
- $updateResult = $collection->updateMany(- B3 Q- c% f, U3 m6 S4 a
- ['state' => 'ny'],7 T8 M1 g. k( x2 `4 P! I
- ['$set' => ['country' => 'us']]4 w4 M1 p8 M- [: b5 o) ?) C
- );
0 g$ H1 C+ a" B& A. h3 | - $count = $updateResult->getModifiedCount();
复制代码 4.查询- $cursor = $collection->find($condition, [# B4 v7 k& M. u( @: x0 G) l8 p
- 'name' => true//指定字段
4 v0 U: t; ?8 H - ]);* _3 Z( u' \4 u$ Y. t0 O$ ~- ~
- $cursor->skip(5);
+ R$ |) H) C2 m. D2 J0 a - $cursor->limit(5);+ v3 Z* u" r% r/ Z; f2 x( C' ] B& o
- $cursor->sort([
/ E" u' b# }- {; `% ]2 \, A: @ - 'time' => -1
; f! V7 w" k: @5 t+ g6 h8 J7 I1 W - ]);
复制代码- $cursor = $collection->find($condition, [
1 c# b& \' T6 s( o; i/ j& i - 'skip' => 5,& A6 ?; _; Z6 e; N, M- Z9 z
- 'limit' => 5,( c" q/ P9 g1 u, x
- 'sort' => [4 a; D) T7 ~. |. u8 B) S$ ^
- 'time' => -1. H" b/ l3 P1 ~. `, ^ H
- ],//排序: y+ K& s9 {; p3 j2 [9 o5 t
- 'projection' => [
* ]3 Z9 `: \/ m; c- Q1 } - 'name' => 1//指定字段
Z5 G9 [9 b; P# A, j0 f5 z - ]
& z, F9 e4 F- M - ]);
复制代码 5.删除- 原6 |: K8 k- h; e/ o0 C" [
- $collention->remove($condition, [2 ^! ^1 R* s# h- q
- 'justOne' => false//删单条) r* r7 Z/ ^4 [# ^% A) {# X2 p
- ]); S. C4 ^1 v( k
- $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);2 X" F7 C6 i7 ]
- $collention->deleteMany($condition, $options);
" j- x4 Y6 q- J7 q$ Z4 u$ d5 F, c
% u: o5 b: s* q# S3 X- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([( E1 Q% j/ `1 j1 J
- '_id' => $tableName//我在自增表中用其它的表名作主键* N. o' C0 M3 h8 K, ~
- ], [
& M5 k$ D) J. k - '$inc' => ['id' => 1]//自增
, k1 F9 y& m0 n% z5 ~ w - ], [$ |8 F7 A4 [* [9 X9 }" A. b
- '_id' => 0- U j: o' o' q/ j& C$ f5 N, K
- ], [, I& l0 w" v, @6 w% s
- 'new' => 1//返回修改后的结果,默认是修改前的1 v, r/ N f1 T z0 f4 F
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([; h) l) `9 g$ s
- '_id' => $tableName
" u) c$ A) y! ]1 N - ], [. G1 c7 s% H8 O" E# U7 ^ a8 r8 j
- '$inc' => ['id' => 1]
0 E4 i) c. |) r5 q% ?& J: c5 P5 Z - ], [! S/ f5 s* A1 d* t3 V) p( r# F5 v
- 'projection' => ['id' => 1],2 |& A4 ~1 t. O) q
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER; O* b8 Q9 k; h/ ~- x6 |9 v
- ]);
复制代码
2 ?3 V, Z. {4 _4 G2 `, z% D: u) Y7 H7 M8 A j! S
|