-
Notifications
You must be signed in to change notification settings - Fork 161
/
Mongo.php
1209 lines (1050 loc) · 33.3 KB
/
Mongo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\db\connector;
use Closure;
use MongoDB\BSON\ObjectID;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
use MongoDB\Driver\Cursor;
use MongoDB\Driver\Exception\AuthenticationException;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Exception\ConnectionException;
use MongoDB\Driver\Exception\InvalidArgumentException;
use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query as MongoQuery;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
use think\db\BaseQuery;
use think\db\builder\Mongo as Builder;
use think\db\Connection;
use think\db\exception\DbEventException;
use think\db\exception\DbException as Exception;
use think\db\Mongo as Query;
/**
* Mongo数据库驱动.
*
* @property Manager[] $links
* @property Manager $linkRead
* @property Manager $linkWrite
*/
class Mongo extends Connection
{
// 查询数据类型
protected $dbName = '';
protected $typeMap = 'array';
protected $mongo; // MongoDb Object
protected $cursor; // MongoCursor Object
protected $session_uuid; // sessions会话列表当前会话数组key 随机生成
protected $sessions = []; // 会话列表
/** @var Builder */
protected $builder;
// 数据库连接参数配置
protected $config = [
// 数据库类型
'type' => '',
// 服务器地址
'hostname' => '',
// 数据库名
'database' => '',
// 是否是复制集
'is_replica_set' => false,
// 用户名
'username' => '',
// 密码
'password' => '',
// 端口
'hostport' => '',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 主键名
'pk' => '_id',
// 主键类型
'pk_type' => 'ObjectID',
// 数据库表前缀
'prefix' => '',
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 开启字段缓存
'fields_cache' => false,
// 监听SQL
'trigger_sql' => true,
// 自动写入时间戳字段
'auto_timestamp' => false,
// 时间字段取出后的默认时间格式
'datetime_format' => 'Y-m-d H:i:s',
// 是否_id转换为id
'pk_convert_id' => false,
// typeMap
'type_map' => ['root' => 'array', 'document' => 'array'],
];
/**
* 获取当前连接器类对应的Query类.
*
* @return string
*/
public function getQueryClass(): string
{
return Query::class;
}
/**
* 获取当前的builder实例对象
*
* @return Builder
*/
public function getBuilder()
{
return $this->builder;
}
/**
* 获取当前连接器类对应的Builder类.
*
* @return string
*/
public function getBuilderClass(): string
{
return Builder::class;
}
/**
* 连接数据库方法.
*
* @param array $config 连接参数
* @param int $linkNum 连接序号
*
* @throws InvalidArgumentException
* @throws RuntimeException
*
* @return Manager
*/
public function connect(array $config = [], $linkNum = 0)
{
if (!isset($this->links[$linkNum])) {
if (empty($config)) {
$config = $this->config;
} else {
$config = array_merge($this->config, $config);
}
$this->dbName = $config['database'];
$this->typeMap = $config['type_map'];
if ($config['pk_convert_id'] && '_id' == $config['pk']) {
$this->config['pk'] = 'id';
}
if (empty($config['dsn'])) {
$config['dsn'] = 'mongodb://' . ($config['username'] ? "{$config['username']}" : '') . ($config['password'] ? ":{$config['password']}@" : '') . $config['hostname'] . ($config['hostport'] ? ":{$config['hostport']}" : '');
}
$startTime = microtime(true);
$this->links[$linkNum] = new Manager($config['dsn'], $config['params']);
if (!empty($config['trigger_sql'])) {
// 记录数据库连接信息
$this->trigger('CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']);
}
}
return $this->links[$linkNum];
}
/**
* 获取Mongo Manager对象
*
* @return Manager|null
*/
public function getMongo()
{
return $this->mongo ?: null;
}
/**
* 设置/获取当前操作的database.
*
* @param string $db db
*
* @return string
*/
public function db(string $db = null)
{
if (is_null($db)) {
return $this->dbName;
} else {
$this->dbName = $db;
}
}
/**
* 执行查询但只返回Cursor对象
*
* @param Query $query 查询对象
*
* @return Cursor
*/
public function cursor($query)
{
// 分析查询表达式
$options = $query->parseOptions();
// 生成MongoQuery对象
$mongoQuery = $this->builder->select($query);
$master = (bool) $query->getOptions('master');
// 执行查询操作
return $this->getCursor($query, $mongoQuery, $master);
}
/**
* 执行查询并返回Cursor对象
*
* @param BaseQuery $query 查询对象
* @param MongoQuery|Closure $mongoQuery Mongo查询对象
* @param bool $master 是否主库操作
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*
* @return Cursor
*/
public function getCursor(BaseQuery $query, $mongoQuery, bool $master = false): Cursor
{
$this->initConnect($master);
$this->db->updateQueryTimes();
$options = $query->getOptions();
$namespace = $options['table'];
if (!str_contains($namespace, '.')) {
$namespace = $this->dbName . '.' . $namespace;
}
if (!empty($this->queryStr)) {
// 记录执行指令
$this->queryStr = 'db' . strstr($namespace, '.') . '.' . $this->queryStr;
}
if ($mongoQuery instanceof Closure) {
$mongoQuery = $mongoQuery($query);
}
$readPreference = $options['readPreference'] ?? null;
$this->queryStartTime = microtime(true);
if ($session = $this->getSession()) {
$this->cursor = $this->mongo->executeQuery($namespace, $mongoQuery, [
'readPreference' => is_null($readPreference) ? new ReadPreference(ReadPreference::RP_PRIMARY) : $readPreference,
'session' => $session,
]);
} else {
$this->cursor = $this->mongo->executeQuery($namespace, $mongoQuery, $readPreference);
}
// SQL监控
if (!empty($this->config['trigger_sql'])) {
$this->trigger('', $master);
}
return $this->cursor;
}
/**
* 执行查询 返回数据集.
*
* @param MongoQuery $query 查询对象
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*
* @return mixed
*/
public function query(MongoQuery $query)
{
return $this->mongoQuery($this->newQuery(), $query);
}
/**
* 执行语句.
*
* @param BulkWrite $bulk
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*
* @return int
*/
public function execute(BulkWrite $bulk)
{
return $this->mongoExecute($this->newQuery(), $bulk);
}
/**
* 执行查询.
*
* @param BaseQuery $query 查询对象
* @param MongoQuery|Closure $mongoQuery Mongo查询对象
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*
* @return array
*/
protected function mongoQuery(BaseQuery $query, $mongoQuery): array
{
$options = $query->parseOptions();
if ($query->getOptions('cache')) {
// 检查查询缓存
$cacheItem = $this->parseCache($query, $query->getOptions('cache'));
$key = $cacheItem->getKey();
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
}
if ($mongoQuery instanceof Closure) {
$mongoQuery = $mongoQuery($query);
}
$master = (bool) $query->getOptions('master');
$this->getCursor($query, $mongoQuery, $master);
$resultSet = $this->getResult($options['typeMap']);
if (isset($cacheItem) && $resultSet) {
// 缓存数据集
$cacheItem->set($resultSet);
$this->cacheData($cacheItem);
}
return $resultSet;
}
/**
* 执行写操作.
*
* @param BaseQuery $query
* @param BulkWrite $bulk
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*
* @return WriteResult
*/
protected function mongoExecute(BaseQuery $query, BulkWrite $bulk)
{
$this->initConnect(true);
$this->db->updateQueryTimes();
$options = $query->getOptions();
$namespace = $options['table'];
if (!str_contains($namespace, '.')) {
$namespace = $this->dbName . '.' . $namespace;
}
if (!empty($this->queryStr)) {
// 记录执行指令
$this->queryStr = 'db' . strstr($namespace, '.') . '.' . $this->queryStr;
}
$writeConcern = $options['writeConcern'] ?? null;
$this->queryStartTime = microtime(true);
if ($session = $this->getSession()) {
$writeResult = $this->mongo->executeBulkWrite($namespace, $bulk, [
'session' => $session,
'writeConcern' => is_null($writeConcern) ? new WriteConcern(1) : $writeConcern,
]);
} else {
$writeResult = $this->mongo->executeBulkWrite($namespace, $bulk, $writeConcern);
}
// SQL监控
if (!empty($this->config['trigger_sql'])) {
$this->trigger();
}
$this->numRows = $writeResult->getMatchedCount();
if ($query->getOptions('cache')) {
// 清理缓存数据
$cacheItem = $this->parseCache($query, $query->getOptions('cache'));
$key = $cacheItem->getKey();
$tag = $cacheItem->getTag();
if (isset($key) && $this->cache->has($key)) {
$this->cache->delete($key);
} elseif (!empty($tag) && method_exists($this->cache, 'tag')) {
$this->cache->tag($tag)->clear();
}
}
return $writeResult;
}
/**
* 执行指令.
*
* @param Command $command 指令
* @param string $dbName 当前数据库名
* @param ReadPreference $readPreference readPreference
* @param string|array $typeMap 指定返回的typeMap
* @param bool $master 是否主库操作
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*
* @return array
*/
public function command(Command $command, string $dbName = '', ReadPreference $readPreference = null, $typeMap = null, bool $master = false): array
{
$this->initConnect($master);
$this->db->updateQueryTimes();
$this->queryStartTime = microtime(true);
$dbName = $dbName ?: $this->dbName;
if (!empty($this->queryStr)) {
$this->queryStr = 'db.' . $this->queryStr;
}
if ($session = $this->getSession()) {
$this->cursor = $this->mongo->executeCommand($dbName, $command, [
'readPreference' => is_null($readPreference) ? new ReadPreference(ReadPreference::RP_PRIMARY) : $readPreference,
'session' => $session,
]);
} else {
$this->cursor = $this->mongo->executeCommand($dbName, $command, $readPreference);
}
// SQL监控
if (!empty($this->config['trigger_sql'])) {
$this->trigger('', $master);
}
return $this->getResult($typeMap);
}
/**
* 获得数据集.
*
* @param string|array $typeMap 指定返回的typeMap
*
* @return mixed
*/
protected function getResult($typeMap = null): array
{
// 设置结果数据类型
if (is_null($typeMap)) {
$typeMap = $this->typeMap;
}
$typeMap = is_string($typeMap) ? ['root' => $typeMap] : $typeMap;
$this->cursor->setTypeMap($typeMap);
// 获取数据集
$result = $this->cursor->toArray();
if ($this->getConfig('pk_convert_id')) {
// 转换ObjectID 字段
foreach ($result as &$data) {
$this->convertObjectID($data);
}
}
$this->numRows = count($result);
return $result;
}
/**
* ObjectID处理.
*
* @param array $data 数据
*
* @return void
*/
protected function convertObjectID(array &$data): void
{
if (isset($data['_id']) && is_object($data['_id'])) {
$data['id'] = $data['_id']->__toString();
unset($data['_id']);
}
}
/**
* 数据库日志记录(仅供参考).
*
* @param string $type 类型
* @param mixed $data 数据
* @param array $options 参数
*
* @return void
*/
public function mongoLog(string $type, $data, array $options = [])
{
if (!$this->config['trigger_sql']) {
return;
}
if (is_array($data)) {
array_walk_recursive($data, function (&$value) {
if ($value instanceof ObjectID) {
$value = $value->__toString();
}
});
}
switch (strtolower($type)) {
case 'aggregate':
$this->queryStr = 'runCommand(' . ($data ? json_encode($data) : '') . ');';
break;
case 'find':
$this->queryStr = $type . '(' . ($data ? json_encode($data) : '') . ')';
if (isset($options['sort'])) {
$this->queryStr .= '.sort(' . json_encode($options['sort']) . ')';
}
if (isset($options['skip'])) {
$this->queryStr .= '.skip(' . $options['skip'] . ')';
}
if (isset($options['limit'])) {
$this->queryStr .= '.limit(' . $options['limit'] . ')';
}
$this->queryStr .= ';';
break;
case 'insert':
case 'remove':
$this->queryStr = $type . '(' . ($data ? json_encode($data) : '') . ');';
break;
case 'update':
$this->queryStr = $type . '(' . json_encode($options) . ',' . json_encode($data) . ');';
break;
case 'cmd':
$this->queryStr = $data . '(' . json_encode($options) . ');';
break;
}
}
/**
* 获取最近执行的指令.
*
* @return string
*/
public function getLastSql(): string
{
return $this->queryStr;
}
/**
* 关闭数据库.
*/
public function close()
{
$this->mongo = null;
$this->cursor = null;
$this->linkRead = null;
$this->linkWrite = null;
$this->links = [];
}
/**
* 初始化数据库连接.
*
* @param bool $master 是否主服务器
*
* @return void
*/
protected function initConnect(bool $master = true): void
{
if (!empty($this->config['deploy'])) {
// 采用分布式数据库
if ($master) {
if (!$this->linkWrite) {
$this->linkWrite = $this->multiConnect(true);
}
$this->mongo = $this->linkWrite;
} else {
if (!$this->linkRead) {
$this->linkRead = $this->multiConnect(false);
}
$this->mongo = $this->linkRead;
}
} elseif (!$this->mongo) {
// 默认单数据库
$this->mongo = $this->connect();
}
}
/**
* 连接分布式服务器.
*
* @param bool $master 主服务器
*
* @return Manager
*/
protected function multiConnect(bool $master = false): Manager
{
$config = [];
// 分布式数据库配置解析
foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn'] as $name) {
$config[$name] = is_string($this->config[$name]) ? explode(',', $this->config[$name]) : $this->config[$name];
}
// 主服务器序号
$m = floor(mt_rand(0, $this->config['master_num'] - 1));
if ($this->config['rw_separate']) {
// 主从式采用读写分离
if ($master) { // 主服务器写入
if ($this->config['is_replica_set']) {
return $this->replicaSetConnect();
} else {
$r = $m;
}
} elseif (is_numeric($this->config['slave_no'])) {
// 指定服务器读
$r = $this->config['slave_no'];
} else {
// 读操作连接从服务器 每次随机连接的数据库
$r = floor(mt_rand($this->config['master_num'], count($config['hostname']) - 1));
}
} else {
// 读写操作不区分服务器 每次随机连接的数据库
$r = floor(mt_rand(0, count($config['hostname']) - 1));
}
$dbConfig = [];
foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn'] as $name) {
$dbConfig[$name] = $config[$name][$r] ?? $config[$name][0];
}
return $this->connect($dbConfig, $r);
}
/**
* 创建基于复制集的连接.
*
* @return Manager
*/
public function replicaSetConnect(): Manager
{
$this->dbName = $this->config['database'];
$this->typeMap = $this->config['type_map'];
$startTime = microtime(true);
$this->config['params']['replicaSet'] = $this->config['database'];
$manager = new Manager($this->buildUrl(), $this->config['params']);
// 记录数据库连接信息
if (!empty($config['trigger_sql'])) {
$this->trigger('CONNECT:ReplicaSet[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $this->config['dsn']);
}
return $manager;
}
/**
* 根据配置信息 生成适用于连接复制集的 URL.
*
* @return string
*/
private function buildUrl(): string
{
$url = 'mongodb://' . ($this->config['username'] ? "{$this->config['username']}" : '') . ($this->config['password'] ? ":{$this->config['password']}@" : '');
$hostList = is_string($this->config['hostname']) ? explode(',', $this->config['hostname']) : $this->config['hostname'];
$portList = is_string($this->config['hostport']) ? explode(',', $this->config['hostport']) : $this->config['hostport'];
for ($i = 0; $i < count($hostList); $i++) {
$url = $url . $hostList[$i] . ':' . $portList[0] . ',';
}
return rtrim($url, ',') . '/';
}
/**
* 插入记录.
*
* @param BaseQuery $query 查询对象
* @param bool $getLastInsID 返回自增主键
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*
* @return mixed
*/
public function insert(BaseQuery $query, bool $getLastInsID = false)
{
// 分析查询表达式
$options = $query->parseOptions();
if (empty($options['data'])) {
throw new Exception('miss data to insert');
}
// 生成bulk对象
$bulk = $this->builder->insert($query);
$writeResult = $this->mongoExecute($query, $bulk);
$result = $writeResult->getInsertedCount();
if ($result) {
$data = $options['data'];
$lastInsId = $this->getLastInsID($query);
if ($lastInsId) {
$pk = $query->getPk();
$data[$pk] = $lastInsId;
}
$query->setOption('data', $data);
$this->db->trigger('after_insert', $query);
if ($getLastInsID) {
return $lastInsId;
}
}
return $result;
}
/**
* 获取最近插入的ID.
*
* @param BaseQuery $query 查询对象
* @param string $sequence 自增序列名
*
* @return mixed
*/
public function getLastInsID(BaseQuery $query, string $sequence = null)
{
$id = $this->builder->getLastInsID();
if (is_array($id)) {
array_walk($id, function (&$item, $key) {
if ($item instanceof ObjectID) {
$item = $item->__toString();
}
});
} elseif ($id instanceof ObjectID) {
$id = $id->__toString();
}
return $id;
}
/**
* 批量插入记录.
*
* @param BaseQuery $query 查询对象
* @param array $dataSet 数据集
*
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*
* @return int
*/
public function insertAll(BaseQuery $query, array $dataSet = []): int
{
// 分析查询表达式
$query->parseOptions();
if (!is_array(reset($dataSet))) {
return 0;
}
// 生成bulkWrite对象
$bulk = $this->builder->insertAll($query, $dataSet);
$writeResult = $this->mongoExecute($query, $bulk);
return $writeResult->getInsertedCount();
}
/**
* 更新记录.
*
* @param BaseQuery $query 查询对象
*
* @throws Exception
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*
* @return int
*/
public function update(BaseQuery $query): int
{
$query->parseOptions();
// 生成bulkWrite对象
$bulk = $this->builder->update($query);
$writeResult = $this->mongoExecute($query, $bulk);
$result = $writeResult->getModifiedCount();
if ($result) {
$this->db->trigger('after_update', $query);
}
return $result;
}
/**
* 删除记录.
*
* @param BaseQuery $query 查询对象
*
* @throws Exception
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
* @throws BulkWriteException
*
* @return int
*/
public function delete(BaseQuery $query): int
{
// 分析查询表达式
$query->parseOptions();
// 生成bulkWrite对象
$bulk = $this->builder->delete($query);
// 执行操作
$writeResult = $this->mongoExecute($query, $bulk);
$result = $writeResult->getDeletedCount();
if ($result) {
$this->db->trigger('after_delete', $query);
}
return $result;
}
/**
* 查找记录.
*
* @param BaseQuery $query 查询对象
*
* @throws ModelNotFoundException
* @throws DataNotFoundException
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*
* @return array
*/
public function select(BaseQuery $query): array
{
try {
$this->db->trigger('before_select', $query);
} catch (DbEventException $e) {
return [];
}
return $this->mongoQuery($query, function ($query) {
return $this->builder->select($query);
});
}
/**
* 查找单条记录.
*
* @param BaseQuery $query 查询对象
*
* @throws ModelNotFoundException
* @throws DataNotFoundException
* @throws AuthenticationException
* @throws InvalidArgumentException
* @throws ConnectionException
* @throws RuntimeException
*
* @return array
*/
public function find(BaseQuery $query): array
{
// 事件回调
try {
$this->db->trigger('before_find', $query);
} catch (DbEventException $e) {
return [];
}
// 执行查询
$resultSet = $this->mongoQuery($query, function ($query) {
return $this->builder->select($query, true);
});
return $resultSet[0] ?? [];
}
/**
* 得到某个字段的值
*
* @param string $field 字段名
* @param mixed $default 默认值
*
* @return mixed
*/
public function value(BaseQuery $query, string $field, $default = null)
{
$options = $query->parseOptions();
if (isset($options['projection'])) {
$query->removeOption('projection');
}
$query->setOption('projection', (array) $field);
if (!empty($options['cache'])) {
$cacheItem = $this->parseCache($query, $options['cache']);
$key = $cacheItem->getKey();
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
}
$mongoQuery = $this->builder->select($query, true);
if (isset($options['projection'])) {
$query->setOption('projection', $options['projection']);
} else {
$query->removeOption('projection');
}
// 执行查询操作
$resultSet = $this->mongoQuery($query, $mongoQuery);
if (!empty($resultSet)) {
$data = array_shift($resultSet);
$result = $data[$field];
} else {
$result = false;
}
if (isset($cacheItem) && false !== $result) {
// 缓存数据
$cacheItem->set($result);
$this->cacheData($cacheItem);
}
return false !== $result ? $result : $default;
}
/**
* 得到某个列的数组.
*
* @param BaseQuery $query