Skip to content

优化multiAggregate操作,可以聚合多个参数 #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -474,8 +474,15 @@ public function multiAggregate($options, $extra)
$groups['_id'][$field] = '$' . $field;
}

foreach ($aggregate as $fun => $field) {
$groups[$field . '_' . $fun] = ['$' . $fun => '$' . $field];
// 支持对于一个聚合操作添加多个字段
foreach ($aggregate as $fun => $fields) {
foreach ($fields as $field) {
if ($fun == 'count') {
$groups[$field . '_count'] = ['$sum' => 1];
} else {
$groups[$field . '_' . $fun] = ['$' . $fun => '$' . $field];
}
}
}
$pipeline = [
['$match' => (object)$this->parseWhere($options['where'])],
Expand Down
3 changes: 2 additions & 1 deletion src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,8 @@ public function count()
/**
* 多聚合操作
*
* @param array $aggregate 聚合指令, 可以聚合多个参数, 如 ['sum' => 'field1', 'avg' => 'field2']
* @param array $aggregate 聚合指令, 可以聚合多个参数
* 如 ['sum' => ['field1', 'field2'], 'avg' => ['field2', 'field3']]
* @param array $groupBy 类似mysql里面的group字段, 可以传入多个字段, 如 ['field_a', 'field_b', 'field_c']
* @return array 查询结果
*/
Expand Down