|
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
% K, M6 D9 c1 Y - . S, N, h$ ]& t6 x8 _
- use MongoDB\Driver\Manager;
- V% ^: `: L- }: }- w. R - use MongoDB\Driver\BulkWrite;
' U7 {% s, ~: H$ T5 c - use MongoDB\Driver\WriteConcern;( y) H+ t, ?3 s
- use MongoDB\Driver\Query;2 m) v9 |& B$ E' n
- use MongoDB\Driver\Command;
/ U }* c4 p4 c& p( R8 f( K - . C ?% P2 E0 L/ _' W5 X
- class MongoDb {
5 O, d, k; T5 F2 ]
+ H% p; ~0 D' N- protected $mongodb;
6 x- m& [4 k: G$ R7 N - protected $database;
1 E5 y9 J* s( Q# I - protected $collection;
+ p. f8 M/ d; O S) ? - protected $bulk;7 H( y7 x: `; V; q
- protected $writeConcern;) }' Z5 ]9 d8 N! X
- protected $defaultConfig3 k/ K2 E' |& a1 b& X/ |' I5 }
- = [
- ^+ n! d; f$ u" Q- j# c" x - 'hostname' => 'localhost',+ R$ w5 G6 Q2 y5 w0 m" W
- 'port' => '27017',
1 D0 J2 f; @4 B3 w. l, b - 'username' => '',
( v, a2 \' A2 p5 j# j7 E - 'password' => '',8 f9 G2 L$ }5 q" @5 `$ p( m
- 'database' => 'test'
/ k \+ Q1 W& e4 n8 w% f( q - ];4 u- i! G g6 M( o
# Z, z9 d' n6 J8 y: @# w& N- public function __construct($config) {
8 t7 Z8 P( P% Z# y) |! t - $config = array_merge($this->defaultConfig, $config);: M$ V) p: k% F8 N3 ~. \ v3 G# i
- $mongoServer = "mongodb://";
* I5 a: L# E; L6 l - if ($config['username']) {
6 _( \* B$ F; B$ L9 @- b! m - $mongoServer .= $config['username'] . ':' . $config['password'] . '@';$ v2 m+ c7 `( ~$ F" C% o
- }
, Z+ S' V( @1 }! U/ B - $mongoServer .= $config['hostname'];, H$ I) q v; _, Q8 T9 L
- if ($config['port']) {
a2 L4 ?( o1 h, u* _ - $mongoServer .= ':' . $config['port']; n# d- \$ [6 G5 ~4 Z
- }, F" J- V% c7 D1 |+ S( G! |
- $mongoServer .= '/' . $config['database'];$ _1 X/ J. |% L) v) T
6 z+ H4 }# T5 `4 W9 q- $this->mongodb = new Manager($mongoServer);
# V8 q3 p: H# y - $this->database = $config['database'];
3 W9 T5 \) P' t) U: o - $this->collection = $config['collection'];
0 X" ^& X, s& N; {9 D& T# x - $this->bulk = new BulkWrite();
" i; A1 C0 @# s3 _- O) `" f - $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
) w4 G! O# @* J" o1 y! t3 G - }5 M8 v1 z$ h7 p, o; v
- ' p P* `, I1 z! H1 l$ S2 q
- public function query($where = [], $option = []) {
& u( n+ C# y5 U4 r4 X4 ?; A - $query = new Query($where, $option);
8 R" v; I! h& |5 i0 P/ \8 n- x - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
% Z9 o' O: y/ }: P0 o - ( } k7 {2 J* J
- return json_encode($result);; x" F1 `7 {+ M j
- }
4 A" R7 J. ]1 U( L4 |" n) t0 q - ) S& G& w+ ^$ G; j: P7 U( t
- public function count($where = []) {
' \! |: W$ T9 N1 m: B: o - $command = new Command(['count' => $this->collection, 'query' => $where]);8 }1 a# T: Y' }+ E {
- $result = $this->mongodb->executeCommand($this->database, $command);
D; O/ v+ Y0 a; O \; J - $res = $result->toArray();
4 Z9 v5 P7 }1 G) | - $count = 0;
" E+ j" n7 f6 ]* ~ n, r5 S - if ($res) {
, y8 E0 P+ W5 C$ Z - $count = $res[0]->n;" Y) r/ p. c9 y$ o7 k
- }6 }: v; j: W) x4 {) d
- ) v! T6 y/ E9 d1 @8 ]5 |7 w
- return $count;
) O* U# i. ^7 i9 r4 ]6 Y' P+ U0 D - }8 P; q/ g) i, ]$ a- p2 O
- 4 n6 _! ~. I9 }" @
- public function update($where = [], $update = [], $upsert = false) {
( J# n7 _* v1 Q/ T: _: P# Z9 j, s" K. D* O; t - $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);% w; q' S6 t- P$ x. D( H3 Y
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
& p8 {( i5 O7 _8 z1 z& i: G - 5 H; N( N8 }0 l, H. I. j1 |% b/ r
- return $result->getModifiedCount();
! P2 D) @0 w, a; G* R! o% y - }
6 r; w- ?/ f' Z3 e1 h
- ?; ^! K: L3 n- public function insert($data = []) {
8 o; r5 s8 V$ P! S" Q' n) X - $this->bulk->insert($data);
% O4 P4 B+ n/ X0 q; X: o d0 i - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);% [; B; V; A( g5 o8 ]* m
- . l) A) ~) P1 W: o5 w+ r6 `
- return $result->getInsertedCount();8 e' Z8 ? V1 `. t' g
- }
/ R$ C3 L/ V& |, A# S$ F - 3 J# j* N' }6 _. o% G8 g- k
- public function delete($where = [], $limit = 1) { l- C" x/ C3 S( _6 \
- $this->bulk->delete($where, ['limit' => $limit]);4 e) q: f& { B9 r5 g
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);1 F& ]- J* ?) r5 h5 h/ R" A$ E
- 5 Q% T! R$ T$ N" t" g
- return $result->getDeletedCount();. ]$ R- P9 S% i, E# f
- }
- t0 g; {" e" C& `+ z - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接2.新增- 原
6 w" o( |% ^4 p6 z! e5 x' l" M. U2 a- t
- $collention->insert($array, $options);
复制代码- 新
/ M3 X1 f+ a4 k, {7 Q5 o
- $resultOne = $collention->insertOne($array, $options);//单% ~! Q" ` C) [( m9 J4 K
- $lastId = $resultOne->getInsertedId();
! f R5 K9 v; U - $resultMany = $collention->insertMany($array, $options);//多! E3 L3 g9 z, |0 z5 m9 O/ Y
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [
F' d5 F% I( J, O - '$set' => $values
4 l* f" m7 q6 W' C - ,[
8 y& X4 E' b. ?: g - 'multiple' => true//多条,单条false
, z* u! ^+ a" B! Z! z7 q( w6 S - ]);
复制代码- 新
3 S2 E" Z# Y# ^* D' [6 H2 J+ n
- $collection->updateOne(
1 r* b4 {) g6 L - ['state' => 'ny'],! f: Z6 I( V+ t- v$ D) f
- ['$set' => ['country' => 'us']]+ C* W# j% R( t$ \
- );, Q" T4 ?2 A2 L
- $updateResult = $collection->updateMany(+ \: }( `1 S \& T; n) O5 s$ Z
- ['state' => 'ny'],
: C4 a6 K" N6 h& q) H: D+ c! `9 _- e2 r - ['$set' => ['country' => 'us']]
: h- k8 p. s3 I+ F$ K0 t - );
) O: S! I" t, i8 r( U - $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
4 t6 a i7 H, _1 H5 O1 N
- $cursor = $collection->find($condition, [% C6 Z. C' R% I4 n2 o
- 'name' => true//指定字段
, l- g: G; e! y1 R( | - ]);0 I% Z' m* X8 d; Y+ `) r3 E8 S, ~. W
- $cursor->skip(5);
, B) }2 L- ^5 a; ~+ X! W2 N) f% Z - $cursor->limit(5);
) W/ V+ \5 R- X! `1 l8 k - $cursor->sort([4 Z6 I3 |% h8 }1 e
- 'time' => -1
# P' |6 K2 W6 s. N - ]);
复制代码- 新/ M% t" |9 c" c6 d- ]# i' q# E& ^) g5 |
- $cursor = $collection->find($condition, [
$ j6 o/ P/ l" y6 n4 f9 K# Z - 'skip' => 5,% L+ \; p) g: m" b
- 'limit' => 5,5 {0 B+ Z4 ^/ W" L# F2 ~
- 'sort' => [
9 K @# S2 `' r6 M/ h. E: @* q - 'time' => -1+ L8 y7 {, Q. A
- ],//排序
2 P. M Z3 o; ] - 'projection' => [1 n/ H- z& b; {4 L3 l1 f
- 'name' => 1//指定字段9 N2 e' H5 T7 W% \
- ]
* o, r, m9 k8 Y |. G - ]);
复制代码 5.删除- 原7 K- p# v$ v3 i, y8 t! O" J
- $collention->remove($condition, [
5 |3 B- l$ [0 A5 X7 g) I - 'justOne' => false//删单条
/ X+ `9 `/ s( _" O; P3 V" Z! D# R - ]);6 p0 y) P4 i0 W X3 K
- $collention->remove([]);//删所有
复制代码- 新
, I+ c6 E# s" `9 P" L9 L- D
- $result = $collention->deleteOne($condition, $options);* S0 l& g' v ^* T0 V$ Q: e
- $collention->deleteMany($condition, $options);4 ]. T0 I9 G% w8 e7 y% E
% {2 h1 ] c$ g( z2 k9 h0 ?5 K: W* _/ [- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([& F' s% _6 E$ ?2 ~
- '_id' => $tableName//我在自增表中用其它的表名作主键4 f( f5 X! ~- e! d2 c# f
- ], [
+ {4 q3 W4 D& ?0 b - '$inc' => ['id' => 1]//自增1 Z; l7 I7 P; R$ s
- ], [# I6 [6 l0 i0 }& t% \1 I
- '_id' => 03 Y, _6 w8 m) F6 X8 R3 I
- ], [* v' N/ Z* N+ U! a; M3 \
- 'new' => 1//返回修改后的结果,默认是修改前的
0 I4 r: L. x. |. u - ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([6 \9 E: X" P! |2 \# i
- '_id' => $tableName
6 |% J. l3 L _: |" [ - ], [
: _5 K, U4 h. M3 } - '$inc' => ['id' => 1]
7 x- z7 N, X2 j8 M* ] - ], [
( G! U- M a* {% Y, q' H8 @ - 'projection' => ['id' => 1],* @, E8 m' k# [$ A9 z+ P, F7 j
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER# P' `2 m# B9 ~4 c( ~/ N
- ]);
复制代码
8 b" s% h6 y0 a2 p: O {+ v
% Q& \6 m' x- C( {3 U |