|
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php
: k+ f( }0 b! Q# L* |! L" [ - , o" M4 T6 O# H& \ R
- use MongoDB\Driver\Manager;/ L& s8 f* L# M: O- {
- use MongoDB\Driver\BulkWrite;
" L5 M3 v7 Y5 P# Z0 Q - use MongoDB\Driver\WriteConcern;4 {( f' X: `* _
- use MongoDB\Driver\Query;1 k5 l6 d5 d7 e( S( F
- use MongoDB\Driver\Command;8 B: w' _$ L. W: _
- ; @( s$ g3 t. x) U+ l' R% `
- class MongoDb {
$ m6 g, c, S: U2 w - $ y3 n4 j5 G; J3 P9 U
- protected $mongodb;
9 _! }, |; m, c9 X( N - protected $database;* `# S0 A: r0 D& Q! x1 Y
- protected $collection;
. r' t- g5 [) [* n2 y - protected $bulk;
+ e& U/ ?4 I! E* _2 _ - protected $writeConcern;( a7 ?8 J7 H0 F2 P) j: T# y
- protected $defaultConfig
7 N6 [$ l; J5 l5 Q9 G - = [' ?, d# _; k h2 l: H( `8 t: ]+ n
- 'hostname' => 'localhost',
/ F& U' d. r4 Z7 d - 'port' => '27017',
; m6 t0 f" M8 J - 'username' => '',+ V8 F7 G' }% O. Q
- 'password' => '',
3 W6 E: O+ v b' |6 {1 j/ F - 'database' => 'test'; Z) F: A2 {! Q$ J4 b" q6 A
- ];( I# G% u2 d0 H) Q
- 0 v5 N/ D0 s& j
- public function __construct($config) {
; H4 ~0 F+ ^7 I' ?0 J! e - $config = array_merge($this->defaultConfig, $config);
: C9 q' F. v' k$ H - $mongoServer = "mongodb://";
! S3 M u5 N% z8 v9 M% E9 z5 r - if ($config['username']) {0 T0 ~3 c$ o* \# f6 X
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';) W, F, [! J0 u' l) `/ }
- }- {1 d Z2 f" {/ p
- $mongoServer .= $config['hostname'];* g) K- j( S: a$ O
- if ($config['port']) {
3 ^ v; G. O* t8 o$ ^: [, \' K - $mongoServer .= ':' . $config['port'];
: F5 _1 u- T5 A2 A# ~/ |* f. Y - }5 G2 T4 H. _5 H* S* D
- $mongoServer .= '/' . $config['database'];
9 y6 P0 h7 u' I5 F
: x% Y; |7 F6 B2 a& [. G& ?- $this->mongodb = new Manager($mongoServer);* K' U% C8 L$ J; x) L
- $this->database = $config['database'];
5 \) P1 `* T5 Q- x - $this->collection = $config['collection'];, o, L D y2 ]' s
- $this->bulk = new BulkWrite();
9 {; T& G5 E1 n. f! w - $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
) ^$ z' r5 o, }7 u; a - }
) l) D! B5 X+ j3 I1 J, w V - , ?) c6 }! z8 W$ }1 R
- public function query($where = [], $option = []) {
7 `+ d- Y4 E% u2 S' j! ]* n, C/ z - $query = new Query($where, $option);2 D& d9 r/ o8 E- g; x
- $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);% C0 X1 G& {& x2 Y, T% z8 M
; Y0 e l5 G7 ?2 \3 ~5 |- return json_encode($result);
1 a% Z+ V$ Y' j6 W a9 B - }
0 W9 ?$ Z! U- t- B! \ - " s3 g H" B6 o# d
- public function count($where = []) {
4 \ b: a% S, @& x$ ]" G: D - $command = new Command(['count' => $this->collection, 'query' => $where]);0 i- B* J- ]! i4 v0 D" ]" E, z3 j; p
- $result = $this->mongodb->executeCommand($this->database, $command);, N; C+ F. B# n4 q1 s
- $res = $result->toArray();
# [% b% ^5 o; H$ W& l2 H+ s# f - $count = 0;
}9 B! Z }5 q* V - if ($res) {' J: G& I* `) Z% D, b) J& \
- $count = $res[0]->n;
+ @4 y* |7 K# O& P+ @- _8 B$ A4 s1 J - }
: R0 J: Y& `6 C% w, h* z) L - 6 y% D3 O9 q# \: F# ^9 T
- return $count;, M5 l& e* [1 i- q
- }
9 ~5 E+ y! G) Z% _1 O% ] ~' j
) {" o6 w2 n5 ]6 g; I- public function update($where = [], $update = [], $upsert = false) {7 m+ x3 n! p* | f
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);4 P3 d/ a7 T+ C- I4 P
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
( i- s+ Q- U1 B) ]+ m* \4 c - ( R$ z ?3 d \/ r9 z
- return $result->getModifiedCount();
" F, o1 q( `7 M. F8 w9 t, c$ x - }4 J& p. l/ n% {5 h- G! n
- % z5 g' L6 q% o9 `: R
- public function insert($data = []) {/ y2 d0 T+ e. A H4 E
- $this->bulk->insert($data);
5 L# V7 Y" V# s. B1 p' s - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);7 r' m% T! _% U$ C
/ K* @+ Q* p' `- return $result->getInsertedCount();
- S) D% N3 a) v" o/ |: }$ s - }
) y: l/ \9 l' A4 J5 R) o" g' q7 R - . o* l; i2 w' [/ T X" f( B/ J
- public function delete($where = [], $limit = 1) {! z! g8 [: |. O" e
- $this->bulk->delete($where, ['limit' => $limit]);: Z4 \% h7 ]) }6 C
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern); ^$ k, q8 s, U" M
- % G6 q7 D# T4 [4 f/ t
- return $result->getDeletedCount();; b# |% C# E) I9 F
- }
; o$ M9 o4 ]5 a# T - }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原8 q0 b6 b' m# O1 {, |' y; Q
2.新增- 原' H- @& h6 V- p- t6 [6 q3 Z
- $collention->insert($array, $options);
复制代码- $resultOne = $collention->insertOne($array, $options);//单
2 E$ n) `8 t$ O, u4 o: Z - $lastId = $resultOne->getInsertedId();
+ e- y( b2 Q' O" k! S - $resultMany = $collention->insertMany($array, $options);//多- e1 u: F& x8 s" f0 ]" Y
- $count = $resultMany->getInsertedCount();
复制代码 3.修改- $collention->update($condition, [
- q( x. ^, _4 N - '$set' => $values) G H& P3 p/ u; M
- ,[
1 X: D3 }9 g6 y, g - 'multiple' => true//多条,单条false2 a/ i$ r5 W/ ]2 D% ~
- ]);
复制代码- $collection->updateOne(
3 F1 K+ d6 w6 y8 J1 C" X - ['state' => 'ny'],
* Z2 r6 F5 N+ a+ T - ['$set' => ['country' => 'us']]" V9 a6 W _) x Q
- );) m1 [- D% e$ U" {* h& g
- $updateResult = $collection->updateMany(
0 p5 T: a* y$ B! h - ['state' => 'ny'],: y1 K, R1 p/ v: G
- ['$set' => ['country' => 'us']]$ v% j: U/ n! d& x
- );
; P8 \$ \' D0 m' \ I) S( b# Z - $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
4 u! _' N' A- F. }3 _/ ?4 |3 `
- $cursor = $collection->find($condition, [
& [% I: X# M7 S$ [ - 'name' => true//指定字段
! @6 `; u2 `" U7 o - ]);( `% ]1 W- L0 j. L& p2 |" D1 T! h
- $cursor->skip(5);8 a; C- U2 k) g3 \+ `
- $cursor->limit(5);0 A; i- R* Z0 i" G0 K
- $cursor->sort([
' T% W9 t& B" q* v7 \/ p - 'time' => -18 G; V3 G& e% d9 v$ R
- ]);
复制代码- $cursor = $collection->find($condition, [7 y- s* F. f, M5 f2 {! M& p
- 'skip' => 5,3 V" h6 v# c8 R0 W0 z
- 'limit' => 5,
' e% D: J' W$ A% {; G - 'sort' => [
$ J8 A+ i, T2 V9 q6 J2 h' k - 'time' => -1
- t& t/ D- j8 ~% J2 D - ],//排序
( J* s0 I( f% X - 'projection' => [
M/ l" J8 |# ?; V2 a4 c - 'name' => 1//指定字段
: o% ] I/ b& v9 D$ H* v c - ]
! s: R& { L5 |5 n& \. k% G - ]);
复制代码 5.删除- $collention->remove($condition, [
/ V" J6 H5 K) ]3 D - 'justOne' => false//删单条/ S, N7 ^. T7 _5 O+ s" u h
- ]);
+ k, D% ]4 F% P% a) l) \ - $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);
/ }0 Y- ~9 [2 m4 d4 Z: R - $collention->deleteMany($condition, $options);, ?/ W: B" g1 B4 q- u9 `8 [
" i" q5 `, z1 C* ?- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([: V/ q! d4 P; e4 [
- '_id' => $tableName//我在自增表中用其它的表名作主键
$ `* e& K" u7 N6 K# l' f - ], [$ T- F. W6 d$ {( b) n
- '$inc' => ['id' => 1]//自增0 P2 C* _8 h% B
- ], [
: g9 A9 c5 L+ S" h - '_id' => 0
' C' {8 V6 E' L( \# f - ], [! p& l2 J% ]% ^; S
- 'new' => 1//返回修改后的结果,默认是修改前的
/ L5 A5 v; b% k- V - ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([- P ^2 k$ L) ]+ O3 L9 k, J
- '_id' => $tableName
4 M; d9 p v$ I; Y% P" e - ], [# r) G. E8 v4 A6 T; E2 g3 h
- '$inc' => ['id' => 1]
# D! c9 w0 e4 L( k; P - ], [
) c3 `4 U W) Y, { f2 M; b, W3 I, }# b - 'projection' => ['id' => 1],
2 O( b- F+ w4 | - 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER( w; @" B. L6 v. R+ B( I3 g
- ]);
复制代码
/ v$ n8 d4 ^: X( `1 X* `$ d' Q
9 R' F0 s/ m# x, x- d9 E |