|
使用 PHP+MongoDB 的用户很多,因为 MongoDB 对非结构化数据的存储很方便。在 PHP5 及以前,官方提供了两个扩展,Mongo 和 MongoDB,其中 Mongo 是对以 MongoClient 等几个核心类为基础的类群进行操作,封装得很方便,所以基本上都会选择 Mongo 扩展。 但是随着 PHP5 升级到 PHP7,官方不再支持 Mongo 扩展,只支持 MongoDB,而 PHP7 的性能提升巨大,让人无法割舍,所以怎么把 Mongo 替换成 MongoDB 成为了一个亟待解决的问题。MongoDB 引入了命名空间,但是功能封装非常差,如果非要用原生的扩展,几乎意味着写原生的 Mongo 语句。这种想法很违背 ORM 简化 DB IO 操作带来的语法问题而专注逻辑优化的思路。 MongoDB 驱动如果使用原驱动的话,大致语法如下: - <?php2 t# M7 W' n" q5 I* j) q1 m4 ?, ?5 G
+ Z( i/ X6 k- \0 B- `" ^, J$ {- use MongoDB\Driver\Manager;
( Z9 H6 ` |" ?; q! n7 F - use MongoDB\Driver\BulkWrite;
$ n+ r* `0 U2 o - use MongoDB\Driver\WriteConcern;
& @0 t$ B: d* X) b - use MongoDB\Driver\Query;
4 w+ @, L. I& z- W" F - use MongoDB\Driver\Command;
( S4 q' a0 P; A3 x - 4 O% t+ N6 H5 b8 T
- class MongoDb {8 I! B( e p8 ^' T" H
8 m& G9 W% P' c$ |$ p- s( m- protected $mongodb;- x; t5 G4 W0 s! ~4 l) c" T
- protected $database;
' k8 N/ I3 V. x+ v - protected $collection;. g0 l0 N9 i2 l# Y
- protected $bulk;
! Y1 Z% `3 b% o1 A' I( Q - protected $writeConcern;
1 ?6 } G* W' B' o7 \ - protected $defaultConfig
8 Y# j0 J/ e9 C# S - = [' i7 x* g5 D L# C
- 'hostname' => 'localhost',
& a1 f& M5 Q+ A+ ]; w - 'port' => '27017',
+ Z6 l0 s2 V/ V4 \+ X) ] - 'username' => '',2 E& Y7 i! L4 ~1 @) G4 L2 o) y. f
- 'password' => '',
# A! |# C$ ?* E1 n7 y3 O - 'database' => 'test'! v2 Z( J8 t' c& ^- _
- ];
! M/ b; z: c. \$ p - 3 s+ k% U$ X3 o0 {- M/ J+ D; Q _4 _
- public function __construct($config) {
& ~1 L) l/ `# w* p& Y$ ?8 R - $config = array_merge($this->defaultConfig, $config);
}% h3 _/ k0 l6 I4 ~' _( z( b - $mongoServer = "mongodb://";
7 r9 F" z. p4 s- e1 r" M) C - if ($config['username']) {+ J( b" y. Z; R, d
- $mongoServer .= $config['username'] . ':' . $config['password'] . '@';9 v8 p* R; j. g5 w5 S! J
- }
0 @7 X8 F9 L. u6 k3 Z8 o - $mongoServer .= $config['hostname'];" E9 v2 z0 ^- v D
- if ($config['port']) {
* ?" T" e3 F4 i - $mongoServer .= ':' . $config['port'];4 @6 h& s$ q2 u# {9 ~2 i d
- }
( {+ A! |5 Z2 p8 R - $mongoServer .= '/' . $config['database'];4 r" G& A. W) a, K5 L7 ` V+ |
3 r( F* ~# M2 b6 F9 a- $this->mongodb = new Manager($mongoServer);# Q/ q( n8 e5 x! g' g5 V& ?
- $this->database = $config['database'];7 D8 l- ^- G3 s# H# L3 Z3 P
- $this->collection = $config['collection'];' R+ X* N4 l$ \/ U5 w5 g/ x' {% ?( V
- $this->bulk = new BulkWrite();
7 i2 O3 `/ m9 u" L d# v - $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
8 s( o( \$ s5 n6 h+ Z* g7 A3 P8 ~ - }
J4 c0 k( U8 @6 t) w% b$ K: A - ' q) i# B3 L# A+ g4 f4 @4 M
- public function query($where = [], $option = []) {2 X `$ n- N# O7 K9 C
- $query = new Query($where, $option);
: c% |5 g8 u1 C, Y: @ - $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);- m/ g" k7 E( X+ d
1 }6 K0 U# @2 e+ k: @ X- return json_encode($result);$ h% T9 t; x4 k. j
- }8 ^8 L( Q8 n) \7 l3 D& ]
- ( W, L! o _0 m8 w5 \
- public function count($where = []) {" C* m- ^4 V0 T' U% m! q- y
- $command = new Command(['count' => $this->collection, 'query' => $where]);
. g. E* }. @( L) g8 i( X - $result = $this->mongodb->executeCommand($this->database, $command);
) x! K! Y& x; e1 ]2 B! E, V - $res = $result->toArray();
# |+ A0 L) } g; ]% j. O9 `7 q2 C - $count = 0;2 T3 G- d4 U& S6 h
- if ($res) {
! P0 |; l* }' B% k! O/ c$ O* H - $count = $res[0]->n;5 B! c9 G+ ]3 o7 d, g) Z, z
- }
! F7 @5 f5 q4 ]2 l* L: g9 [6 _
( L7 b6 o- t/ d- return $count;
7 h N$ _( b/ u0 K+ Y - }$ w* g$ g" P' B- h
- ( s( S1 z8 g6 _: y5 f' {2 _- M
- public function update($where = [], $update = [], $upsert = false) {& R& d1 K% f2 I4 k/ s" ^
- $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
% F# N* Z: n" s - $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
. y" x+ |1 I8 D
, a# G3 l6 P. {! S, ]# w3 z; {- return $result->getModifiedCount();
; a1 `" E; q9 o. j' @ - }
" ?0 a: R6 W n# r. P" }! q, r
* e' Y/ x* t5 O8 y/ G) F: B- public function insert($data = []) {" L! ^# b+ ]* x
- $this->bulk->insert($data); o6 Y5 n# I+ A/ v) O: [' ]6 l* S3 N
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
2 l* `! ~6 q6 s' _ - 0 K% E# @& \; f' K* c* }
- return $result->getInsertedCount();
+ H( [( z j1 ^6 l" Y: Y: W - }8 [) ^* G$ z9 G1 a) i+ ~
! W8 Y4 o6 ]$ \; F- public function delete($where = [], $limit = 1) {; d. y' Y2 F" ~/ y% d
- $this->bulk->delete($where, ['limit' => $limit]);& f* M+ O$ R0 s! y P; d. w- W
- $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);- r4 y% b/ [4 M( m4 V# Q8 q/ {
- , m; l8 P, Q/ p$ j: ^, y" B) h$ d
- return $result->getDeletedCount();
% ?% l' n; a3 O# y& G - }$ C/ F. K2 b' V$ a
- }
复制代码这样的语法和之前差异太大,改动不方便,换 PHP MongoDB 库 MongoDB 库1.连接- 原* D8 k( w6 B8 t. H7 @) }4 j: z
2.新增- 原* f+ ?8 q; A) p( E% C* E" q2 V( j
- $collention->insert($array, $options);
复制代码- 新
! X& f$ F- L) {# ~1 O9 k
- $resultOne = $collention->insertOne($array, $options);//单1 T8 G& J b3 f
- $lastId = $resultOne->getInsertedId();
, ?) m2 q0 A+ Y+ m& p - $resultMany = $collention->insertMany($array, $options);//多
8 F2 P& B# J+ P* ?; a - $count = $resultMany->getInsertedCount();
复制代码 3.修改- 原
& ]" P0 k: T# f8 ~' J% J7 o
- $collention->update($condition, [
& m4 }0 R2 t8 X5 C - '$set' => $values( m6 |" K& `4 t! j: N- H
- ,[
, ]7 k# j! T( l2 t1 n - 'multiple' => true//多条,单条false! a7 R. | j) b6 m4 p& Q+ H
- ]);
复制代码- $collection->updateOne(
) L5 j. d+ s4 i7 ]- N9 H' g! n - ['state' => 'ny'],' c/ U i7 S/ F' T/ X
- ['$set' => ['country' => 'us']]! ?% D4 w2 r. |3 ^/ M0 F5 |
- );1 `) g7 _1 G. _
- $updateResult = $collection->updateMany(
& {9 B# J8 a5 [# M - ['state' => 'ny'],. a* ^& e4 l' u
- ['$set' => ['country' => 'us']]
: Y% Q7 ^8 v4 E2 X { - );
. I! J0 t# h, Z- J( J+ g - $count = $updateResult->getModifiedCount();
复制代码 4.查询- 原
8 H1 w2 }! t# P, M) W9 J
- $cursor = $collection->find($condition, [
9 n2 ~, d$ V9 H - 'name' => true//指定字段
: W" x' d8 U: n3 k: S - ]);
; G, d2 ?/ D9 p4 f7 m" ]# g - $cursor->skip(5);
, @) @ f+ b: V. U# ^* J - $cursor->limit(5);
7 l3 }1 U6 `% J- u6 Q) H- l" P4 p8 ] - $cursor->sort([% a4 {5 p: A2 n' Z. z" l
- 'time' => -1
3 A8 r! _* F) b3 h$ _& m - ]);
复制代码- $cursor = $collection->find($condition, [: J- L% v6 |0 W* t3 v6 M
- 'skip' => 5,& e0 u3 _% h9 M' `9 @7 N3 a
- 'limit' => 5,2 }3 q0 m( S- m: W
- 'sort' => [, Y0 N* T/ w) n
- 'time' => -1 ]0 [6 p; U% H1 W- S3 q
- ],//排序7 l u& N3 d U+ M' @' R0 l$ m* N6 c6 r
- 'projection' => [! L1 a8 }3 A; W# I0 V; |4 c# P
- 'name' => 1//指定字段
3 x' D1 E) c% W! O9 { - ]
: V% |0 [7 p& [$ N U! T9 y - ]);
复制代码 5.删除- $collention->remove($condition, [
- B" ]4 w, V/ J5 Q. v - 'justOne' => false//删单条. W5 J- [8 [; d% B
- ]);
. O+ L" Z. `) S7 q - $collention->remove([]);//删所有
复制代码- $result = $collention->deleteOne($condition, $options);6 i/ j0 L- |5 C8 C$ c
- $collention->deleteMany($condition, $options);
" o1 z) z% i1 Y# o0 [* O' ~, a - 4 A/ ~; C# k" u$ s5 a( q0 _5 h7 `
- $result->getDeletedCount();
复制代码 补充有些人可能习惯以类似 MySQL 的自增 ID 来处理数据,以前可能使用 findAndModify() 方法来查询并修改: - $collention->findAndModify([
8 b7 \9 X( g/ Z$ J3 q - '_id' => $tableName//我在自增表中用其它的表名作主键) M0 [* L/ w/ A, c
- ], [9 Z) n7 M, M( s5 F# Y) A
- '$inc' => ['id' => 1]//自增
: @7 S2 X0 S* g3 }7 p) C' v$ n - ], [( D m- O- o5 w: ~, O" \/ U
- '_id' => 0
( r/ U, A* [* i2 K - ], [
' b" z2 @; P, B8 \* y - 'new' => 1//返回修改后的结果,默认是修改前的1 H+ T, q. x; z( s0 W
- ]);
复制代码现在使用 MongoDB 库的话需要修改为: - $collention->findOneAndUpdate([7 N) Z$ b% W( ^
- '_id' => $tableName- u) _* s! a' x4 [
- ], [! B- G" b# U$ A2 i
- '$inc' => ['id' => 1]1 u$ \! X/ r H: P# F. b( i
- ], [/ p" w, U9 m" R8 F7 Z+ S! z* E. g
- 'projection' => ['id' => 1],0 N4 c8 o! s+ Q+ _0 I: g/ i
- 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER0 U ^, x4 Y2 g
- ]);
复制代码 ( H4 w# X+ L( l( N8 w
' j% ?' d: G+ \* O9 F% Z" a% F
|