使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
# C* g4 l7 U0 _( p* N6 R - : l) r- M! s0 g3 M; v
- use MongoDB\Driver\Manager;
6 }. o" O: T* \" C - use MongoDB\Driver\BulkWrite;% Q U/ f- S6 q4 a
- use MongoDB\Driver\WriteConcern;
. s' u8 d/ X8 B - use MongoDB\Driver\Query;
, S1 z N3 F+ s" M - use MongoDB\Driver\Command;. x" m& S7 J3 Q5 m, x( [
- : e; \" K" K3 E7 ?9 \4 ]* i
- class MongoDb { n8 T: x- |+ ?, H5 p- q5 p
- 4 {9 ?% L+ d1 k9 Q
- protected $mongodb;
+ X$ a" j K4 W7 P/ b1 v - protected $database;
! K5 |6 [) _/ ^& t# ] - protected $collection;' _9 L: x; f p4 Q
- protected $bulk;
9 W8 x( \; v4 T& P5 b7 i - protected $writeConcern;, v; n& Q, \9 {* E, t2 P& e
- protected $defaultConfig" [8 A( {; M) f0 u" K2 v
- = [: j! z" h1 y) I+ P2 s9 ~
- 'hostname' => 'localhost',6 q2 M; q& C: O' |7 V7 i
- 'port' => '27017',4 {4 [! R3 e" y! w% [# Z* H
- 'username' => '',
9 \% a# _( m' [/ \1 E. B1 q4 f) ?. { - 'password' => '',5 U" G* J" G, M* _- E
- 'database' => 'test' k; ?' ]$ O+ L; x) u9 y/ z, Z- y
- ];
0 {4 U$ z( L, T/ T - # N6 f2 X/ s+ m
- public function __construct($config) {
- u) Y. |7 A5 h$ [# a - $config = array_merge($this->defaultConfig, $config);
2 M' W% }1 t2 R9 G - $mongoServer = "mongodb://";
0 m$ |% y& F, B - if ($config['username']) {
6 S) x* m( p* H" | - $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
' Z9 H& l8 Z; T4 \0 g. i - }
) u) j( N# C) [" b1 m4 t9 t - $mongoServer .= $config['hostname'];8 h6 o' {0 j3 A- J& J3 p
- if ($config['port']) {8 u# T7 x3 b3 O2 Q* X
- $mongoServer .= ':' . $config['port'];! I0 I5 Y- G4 X7 `. o: ~
- }
) D9 {. B, c& B, N F, ~! w - $mongoServer .= '/' . $config['database'];
: F; d5 s7 p* f- u; {
, f. k% A+ u* F$ T3 v E- $this->mongodb = new Manager($mongoServer);
0 b! {6 G2 ~6 I- A# ?% e - $this->database = $config['database'];
6 e3 } M$ k" X( q( J - $this->collection = $config['collection'];
, H% `1 ^- F8 z2 R6 ?& ]4 Q* m - $this->bulk = new BulkWrite(); q8 C8 w# [8 r/ {" p( I. h
- $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
( S7 M9 R! D. V/ w9 T8 U - }* T: ]) L2 a: y7 o+ |$ Q
- 3 s! T1 E2 Y( c1 Q( M7 `
- public function query($where = [], $option = []) {9 l9 Y- Q4 m* G! }
- $query = new Query($where, $option);
9 g4 @8 p. x6 F7 o' O* [ - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);3 s" V( [ n% p( e$ g$ \
- 5 t% e- F8 M$ h
- return json_encode($result);
5 @: n. U0 D) p4 }, m; Q, ^- | - }- M K- f# _6 Z* Z: }2 ~1 u
- ' U" f; C' W6 b% G# q2 w+ U2 S& `
- public function count($where = []) {. M9 H% p, v+ i
- $command = new Command(['count' => $this->collection, 'query' => $where]);
, J. g. h& Z$ L4 W) X - $result = $this->mongodb->executeCommand($this->database, $command);& P# S$ j i7 E
- $res = $result->toArray();
6 U3 J( |( t5 W$ z1 K - $count = 0;
7 G( w v4 s" m$ t, v - if ($res) {9 x1 Y2 u. S+ ]+ i) {6 @4 m
- $count = $res[0]->n;: j2 l9 Y& q' q5 N( s5 D: Z; j
- }
3 |, M8 B/ ^+ V8 Z8 b( j - ) H" Y- g% l" Y
- return $count;
# r9 g* Y, _ R - }$ P8 O+ n) y# X! T
% M# I2 n2 Q' |! `8 R* ~ J' v% E- public function update($where = [], $update = [], $upsert = false) { {/ s- ]3 |: `& o+ @( |
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);. M* L3 W# }0 t1 v; p8 w
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
: k; F# t% Q2 n
1 x8 ]9 K; f2 h4 [8 m- return $result->getModifiedCount();
* F/ K! J! W4 n7 I% O: F - }/ Y0 y9 j n* A/ I" q; O
2 a' {# f" v" F) |* W( E" h- public function insert($data = []) {
6 H1 x! ]5 r8 z: I. y E - $this->bulk->insert($data);
: f- |5 p# Y1 b4 w - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);0 h* B0 Y; F4 s! C8 J
3 A1 Q A: [- w# ^: O! A- return $result->getInsertedCount();
6 p5 ]) ^8 h; k2 }+ K; ? - } V5 ~/ |- l0 A4 g1 X
7 ^* V3 u' C2 Q. G* Y- public function delete($where = [], $limit = 1) {
1 Z4 y; {8 {3 O: a9 { - $this->bulk->delete($where, ['limit' => $limit]);
- q/ w% I; n& i& ?; @ - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);% w- F8 V1 b% p0 a+ S
/ X1 Z- Q5 Y. _* k+ I/ A! m- return $result->getDeletedCount();
6 @5 o# k9 o4 v6 e7 F1 s$ [ - }
) h% K9 ^, F8 t9 ~2 Z+ K - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原
2 }, N+ D. X9 }: J# V7 y: O9 I
- 新# K8 s3 [7 A! T! r. Z E) Q: I
2.新增- 原
. s% k* E9 C2 l; x! q8 l% S* o
- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单
: _7 p/ i& J5 t; m% {& m - $lastId = $resultOne->getInsertedId();& K6 X. H: u6 z, L% S
- $resultMany = $collention->insertMany($array, $options);//多
. r q D; }: X5 L' v; f - $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [
& a$ K$ M* ]+ l$ b8 d/ k - '$set' => $values& o+ q# G0 p' O
- ,[2 W* ?4 {& F7 v( P' K
- 'multiple' => true//多条,单条false Z& y9 @( H. {& \8 ~
- ]);
复制代码- $collection->updateOne(
" [$ _9 h! b2 F$ `, L9 v0 y - ['state' => 'ny'],' v& {" L6 y$ T
- ['$set' => ['country' => 'us']]9 o$ v1 t' o- M; s9 P% X
- );
+ V" b8 c0 i' V( R - $updateResult = $collection->updateMany(
+ A* d: V7 I2 g6 l a3 U/ ^ - ['state' => 'ny'],
/ s( z+ Q2 [. v5 F - ['$set' => ['country' => 'us']]
. @5 S7 g5 C; G! m' W3 _" y - );& w1 O1 Z3 U$ w. w& x r
- $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原- d( b/ d% M- d! g1 ?1 ^$ Y
- $cursor = $collection->find($condition, [+ Y0 ?% u1 x( s$ N3 ~
- 'name' => true//指定字段
+ \+ T4 A( e! u2 p8 A, x9 D - ]);
: c+ E# ^3 `* `1 h - $cursor->skip(5);, [# i, o% g: }" Z5 Y& C- d7 D9 `
- $cursor->limit(5);
7 T, U6 ]3 z7 ?. F% Y# `2 B - $cursor->sort([
) D# n! a- c1 `, A) z. i - 'time' => -1
' M4 N7 r- _9 N$ N - ]);
复制代码- $cursor = $collection->find($condition, [
* g3 t' C/ P0 A0 t4 o1 W* z - 'skip' => 5,
, c- M3 R! w, b7 t" N3 W9 o - 'limit' => 5, q) b* _8 ]& E* {5 P
- 'sort' => [% J5 p6 k, u; T1 P
- 'time' => -10 i1 M' z4 P: X" V, G
- ],//排序: y! v, |" K M* z
- 'projection' => [' N; g5 O; N; X! Q7 i* o* x
- 'name' => 1//指定字段
0 m: ?6 ^8 Q# {" ]3 Z/ x5 n( ? - ]
9 u- u, }* G4 ~6 ] - ]);
复制代码 5.删除- 原% w! L' u/ Z; D" l" z& T0 o0 `
- $collention->remove($condition, [2 u8 r9 b( j7 K8 i
- 'justOne' => false//删单条
X9 {1 { ~5 n# K- v* O& G - ]);/ f7 k, x$ ]4 O& x `, i0 g q
- $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);8 o. r5 R# H: S9 X1 }6 \ `
- $collention->deleteMany($condition, $options);4 ]1 |, ^# H9 R7 j6 r! n9 o
/ ]4 {; \" D: f- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([
3 q0 Y4 l5 R$ Z* i. o) }- f - '_id' => $tableName//我在自增表中用其它的表名作主键% p( `6 }( H4 X! L3 b! {/ U- U& ?
- ], [. c4 ^# Y; d& h: T- ~) K; ]
- '$inc' => ['id' => 1]//自增* a" p+ s5 x% U" l5 `+ L: n, L
- ], [( u7 |! }, _+ e. t2 Z' x
- '_id' => 0
+ R7 b' X: h, w& V - ], [
; Y( Y) E' p6 ^ - 'new' => 1//返回修改后的结果,默认是修改前的: E0 l# O9 V+ \4 @
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([# d2 |! P# w5 i) z: |: f
- '_id' => $tableName1 a9 R( \, o' W
- ], [
" {( q% H/ m- n) Z - '$inc' => ['id' => 1]
& s5 G3 h' T1 t, x {, k. L - ], [
. Q' _, ?% w! s( k - 'projection' => ['id' => 1],5 k; k) n7 y9 B4 U% I6 M; K' l; N
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
8 q& ~: o9 D9 {& X - ]);
复制代码 2 B* m3 x a# W% I4 N
: G. N* u2 U9 D- s5 ? |