E:\www-root-20211223\項目名稱\vendor\topthink\think-orm\src\db\builder\Mongo.php
/**
* 多聚合查詢命令, 可以對多個字段進行 group by 操作
*
* @param Query $query 查詢對象
* @param array $extra 指令和字段
* @return Command
*/
public function multiAggregate(Query $query, $extra): Command
{
$options = $query->getOptions();
[$aggregate, $groupBy] = $extra;
// print_r($aggregate);
$groups = ['_id' => []];
foreach ($groupBy as $field) {
$groups['_id'][$field] = '$' . $field;
}
// Array
// (
// [sum] => 1
// )
// Array ( [sum] => $update_date )
foreach ($aggregate as $fun => $field) {
// $groups[$field . '_' . $fun] = ['$' . $fun => '$' . $field];
$groups[$fun . '_' . $field] = ['$' . $fun => $field];
}
$pipeline = [
['$match' => (object) $this->parseWhere($query, $options['where'])],
['$group' => $groups],
];
$cmd = [
'aggregate' => $options['table'],
'allowDiskUse' => true,
'pipeline' => $pipeline,
'cursor' => new \stdClass,
];
foreach (['explain', 'collation', 'bypassDocumentValidation', 'readConcern'] as $option) {
if (isset($options[$option])) {
$cmd[$option] = $options[$option];
}
}
// print_r($cmd);
$command = new Command($cmd);
$this->log('group', $cmd);
return $command;
}
使用案例:
<?php
namespace app\pro_admin\controller;
use think\facade\Db;
class HzbTest extends \app\BaseController
{
# http://xxx/hzb-test.html
public function test(){
try {
$obj = new \app\common\model\pro\SubmissionRecord();
$return['data'] = $obj->where('submission_type','4')->multiAggregate(['sum' => 1],['table_id','company_id']);
// $return['sql'] = $obj->getLastSql(); // 沒什么用 打印是空
} catch (Exception $e) {
$return['code'] = 500;
$return['msg'] = $e->getMessage();
}
return json($return);
}
# http://xxx/hzb-test.html
public function test1()
{
try {
$obj = Db::connect(env('mongodbii.connection_name'));
//group分組:_id為null匹配所有記錄
//total為新起名的字段:$sum值為子文檔字段表示求和該字段符合條件的記錄,類似sum
//count為新起名的字段:$sum值為1表示統(tǒng)計復合條件的記錄總數(shù)草姻,類似count
$pipelines = array(
['$match'=>["site_id"=>env('hefeixhapi.hfzjxh_ksiteid')]],
['$match'=>["submission_type"=>"4"]],
[
'$group'=>['_id'=>null,'count'=>['$sum'=>1]],
],
['$project'=>['_id'=>1,'total'=>1,'count'=>1]],
);
$submission_record = $obj->name('submission_record')->cmd([
'aggregate'=>'submission_record',
'pipeline'=>$pipelines,
'explain'=>false,
]);
dump($obj->getLastSql());
$return['data'] = $submission_record;
// db.cmd({"aggregate":"submission_record","pipeline":[{"$match":{"site_id":"xxx"}},{"$match":{"submission_type":"4"}},{"$group":{"_id":null,"count":{"$sum":1}}},{"$project":{"_id":1,"total":1,"count":1}}],"explain":false});
} catch (Exception $e) {
$return['code'] = 500;
$return['msg'] = $e->getMessage();
}
return json($return);
}
}