使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
9 ?; c! N M8 Z0 }% I* I6 k# a, N* U - # J+ G/ F+ M8 C& n5 N+ l- ~, p
- use MongoDB\Driver\Manager;6 {/ `8 o9 i$ ?% |' N
- use MongoDB\Driver\BulkWrite;. `! \6 r& b6 b) C' v- n
- use MongoDB\Driver\WriteConcern;
, Y. T) G/ X! B* K( a3 N, h' i6 w# ^3 a - use MongoDB\Driver\Query;
- A; l2 x! a/ H) K - use MongoDB\Driver\Command;8 C, i2 a+ ~/ U# X) @' ~* i2 [
- 4 c: W2 `$ Q* I" f
- class MongoDb {, h* O4 [( m/ V- i6 ~) y
- 5 [, I/ {& \9 `7 c4 I" i& K G
- protected $mongodb;2 q0 V5 `! J' h2 `
- protected $database;+ @ @ f" c0 b9 g7 j& z0 d9 v/ n
- protected $collection;
h+ y) A6 M$ O* [ - protected $bulk;! B0 Z8 d3 z- }* g0 k
- protected $writeConcern;
% b/ Q# j7 D& U' Y - protected $defaultConfig
6 p1 {; m, u0 ^& q4 w0 I - = [! h& k2 e; Z8 Y
- 'hostname' => 'localhost',. C, `2 q/ O; |% }0 S+ g
- 'port' => '27017',% T3 q; a! s" n
- 'username' => '',% n7 z1 F! i- w2 }5 K2 f
- 'password' => '',' H" |! h0 o; J
- 'database' => 'test'. Z' M+ W5 F3 p4 k1 k# S
- ];4 E7 t* |# J9 z7 h# e
6 h9 z( m: f/ U+ n5 U/ q: q- public function __construct($config) {
! I9 T; g! e+ @ t% O - $config = array_merge($this->defaultConfig, $config);
) s/ v7 }( F- r4 E- F2 S - $mongoServer = "mongodb://"; W( P- {; _2 P* T# c- v1 k- `
- if ($config['username']) {
V1 n% y5 R$ n/ J9 v3 o - $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
. W& d& q! }! w# p& \2 A - }# I: i; ~4 r' V8 g' x% m1 f
- $mongoServer .= $config['hostname'];
: }3 v+ x: h7 W( e$ x0 I6 ~9 e - if ($config['port']) {/ }" i4 p6 p0 @: R( I& _5 {# p6 r
- $mongoServer .= ':' . $config['port'];
3 ]3 _7 Q6 R/ L' f( [! O) r3 i - }
5 c I; D. ~, n( G) m. n - $mongoServer .= '/' . $config['database'];7 ]$ P. n) C% c5 o. r: Q% W
- 1 N: y% v& S+ B' c4 o: Y
- $this->mongodb = new Manager($mongoServer);
* i* @; K; A3 X. Q( n - $this->database = $config['database'];* _( Y3 x2 `0 @# A; \
- $this->collection = $config['collection'];
" M" M- A( ?6 ~( d' | - $this->bulk = new BulkWrite();
0 M( C; o- [0 |5 k# l: h7 b! g - $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
1 E5 t- s0 _3 ^3 L: G - }, |4 y. ?' i6 f) @# I. I" B4 \
- 1 f& s% c( @* s' V
- public function query($where = [], $option = []) {
8 a. A; { u* }4 [- {7 w+ y& z - $query = new Query($where, $option);
3 K& \2 F; c4 O. e) |( E( | - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
1 O/ D V* v1 T8 s% } - 6 _6 B6 M/ C! h% d F( [5 }
- return json_encode($result);
7 r0 m! `' F- o2 M - }
7 ^; |% |4 Y; g( q1 f8 o/ O - % M) x! W3 [ R5 n8 c8 w+ @
- public function count($where = []) {2 {& R& y2 f# P* y
- $command = new Command(['count' => $this->collection, 'query' => $where]);3 v8 a# E C, K$ `9 v' J* L+ ]
- $result = $this->mongodb->executeCommand($this->database, $command);
$ Z/ k, ^& P$ p7 \" z - $res = $result->toArray();
, d: c2 W' E* }6 M% Q' i8 j6 f - $count = 0;, P7 ], w0 i/ E7 U
- if ($res) { C5 p0 G# l) M+ f7 R! J$ o
- $count = $res[0]->n;
* }/ F7 {3 g$ u5 h! C4 p0 F - }6 f+ G, T7 s% t0 a
- 1 I G2 t) ] {" h3 X
- return $count;
4 Q; t+ `1 j: ~$ n5 E - }( _6 d, N3 H& X3 F
- / k- N& ]5 X2 J; O
- public function update($where = [], $update = [], $upsert = false) {( B# T# }& [" B [/ a- c! u
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
% M* |: \7 {0 V# Q: e- z - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
4 s* l1 F5 ?$ h
7 F3 J0 z2 s: @( J8 g8 p$ x- return $result->getModifiedCount();
! n( O( s7 F8 I& |4 ^3 Q - }( {" i0 D+ C' p' i5 R3 }
- 0 _& |3 z/ J3 F: Q3 }
- public function insert($data = []) {5 J& {. ~. ? O6 n6 J& p% U6 T
- $this->bulk->insert($data);
& u$ M, Y; Y. |4 f4 q% l( G' o - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);. E/ `: z( k: I. R
E. f! D( ~. | @4 x- return $result->getInsertedCount();" W" K: a) d0 d4 }
- }5 }: m) Z# s" ~. ]1 S$ x7 y
4 c) g' [' N! \6 d+ {1 d, B- public function delete($where = [], $limit = 1) {
* L5 E. q9 s/ i! [3 S% E; v - $this->bulk->delete($where, ['limit' => $limit]);
5 T5 T& h" ]: E# h9 P3 {, D3 U - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
5 Q; Y! E9 o4 b# H - ; w1 @2 r8 Y9 V3 M. T" v% z
- return $result->getDeletedCount();+ _& T9 l. S" m x( P" \
- }: p3 T' N$ p! A0 F2 Z2 c* |. v
- }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原( X7 k2 k' ~- V+ s3 Q+ L1 H+ r W9 d
- 新3 x5 d# C6 l; f! F# ?" K
2.新增- 原$ ?# q, C2 Z5 s. M. e& L$ m
- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单( e6 M% J- `0 s7 n) w
- $lastId = $resultOne->getInsertedId();
+ z' @. Y' A( T - $resultMany = $collention->insertMany($array, $options);//多
. @% _% C' }+ ]# i+ s - $count = $resultMany->getInsertedCount();
复制代码 3.修改- 原
, t6 y$ I8 ?: _' @" `& M! R
- $collention->update($condition, [& ?8 e* M( e8 G* k6 s
- '$set' => $values2 {. H' o. L/ o s5 d# e
- ,[4 [: J# @+ i6 ^$ j3 {# M) r6 L' @
- 'multiple' => true//多条,单条false
5 y! ^& C0 M) B5 p( T - ]);
复制代码- 新
( r2 y& i7 R5 Z: L& d C, v% P
- $collection->updateOne(
9 ~; g9 w8 G" |% I$ s% K; w. x - ['state' => 'ny'],; e& ^" @6 u$ E1 c6 Z
- ['$set' => ['country' => 'us']]! I" ^) Y' W3 `
- );
% _& T! L: G! J: m - $updateResult = $collection->updateMany(4 i) j) n( P7 n
- ['state' => 'ny'],
. m) @1 _- F# k6 _" c! f - ['$set' => ['country' => 'us']]
W. ?5 g* x+ B6 I - );
! G3 F& { r' s; p5 M7 N5 W - $count = $updateResult->getModifiedCount();
复制代码 4.查询- $cursor = $collection->find($condition, [9 j: D* m. B7 E! K" D5 f
- 'name' => true//指定字段
( |1 _9 X ~ O! A& M! \1 R S - ]);. q( U0 f, B C, V0 q6 ~
- $cursor->skip(5);9 Z2 U/ N) v! r1 [/ \ W1 q# ?
- $cursor->limit(5);$ b5 K" e( T9 K; p* C
- $cursor->sort([/ Q# x, B6 T2 L- Q
- 'time' => -1
$ q- L" K0 \# Q" H - ]);
复制代码- $cursor = $collection->find($condition, [
3 h/ Y0 f# D( x4 O1 ?' F0 {% k - 'skip' => 5,7 c" M7 X. {" H1 }' @* z7 w
- 'limit' => 5,
, n( g1 B! H Z! V$ Z - 'sort' => [
" l* d t' o& ]/ s7 b9 d0 f - 'time' => -1! i# ? n, g ~5 i6 ~' ?& ^! v
- ],//排序
, A: K; E6 |. o7 u - 'projection' => [+ j7 O2 f( I8 u# X1 b
- 'name' => 1//指定字段+ T; ?, V' c* ~6 X: T( B
- ]
( U; }' f: R: c7 N - ]);
复制代码 5.删除- $collention->remove($condition, [5 Q4 t& L& y. C. }8 M, Z9 D
- 'justOne' => false//删单条
! X2 R4 v W' y - ]);
4 w. W0 I2 i4 P' q8 \% X2 r - $collention->remove([]);//删所有
复制代码- 新+ J0 w* M0 x1 }& t- ^% p
- $result = $collention->deleteOne($condition, $options);
4 i0 J+ E% c! A( N - $collention->deleteMany($condition, $options);
, ^; ^6 B1 Q# m% @/ k% p; i6 k* j - . Z+ J- U4 x3 L$ l( B" Q0 n2 {3 ]
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([
3 S4 r# g) V/ p0 g) h. h9 u - '_id' => $tableName//我在自增表中用其它的表名作主键
' b D, M2 t. U' F+ i - ], [
" Q; n/ g ]( m - '$inc' => ['id' => 1]//自增
" M! @/ P* [! x5 z6 r1 p - ], [
, V9 O$ l7 y* Z7 M& J0 p* n - '_id' => 0
) x6 t# I9 |: h - ], [
, ` h- {) L0 Z1 @7 l - 'new' => 1//返回修改后的结果,默认是修改前的
% U4 d2 a A. t; t3 E - ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([. P% ~0 O$ J+ W( H' E
- '_id' => $tableName3 }0 d8 Y6 x! f% }
- ], [5 }) ^9 i; I* A$ A. @
- '$inc' => ['id' => 1]
% ], T+ L* _: Y) | - ], [. j" k5 g2 }8 {+ I
- 'projection' => ['id' => 1],
9 _% F. ? D# f6 L" B - 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER, r7 i: C3 ?) U; X# s: G4 F$ V" n
- ]);
复制代码
: l' W( m0 c7 X7 k
( W6 j" ?- m T1 `2 n7 R |