问题描述
在 mongodb laravel 中使用 $bucket
运行 $group
时出现上述错误。
输入集合:
{
"id": "n54qllhzwdlxqvy","season_id": "vl7oqdehzjxr510","status_id": 8,"venue_id": "","referee_id": "","neutral": 1,"note": "","home_scores": [0,0],"away_scores": [1,"home_position": "","away_position": "","coverage": {
"mlive": 0,"lineup": 0
},"round": {
"stage_id": "ednm9whz7xoryox","round_num": 0,"group_num": 3
},"updated_at": "2021-05-03 16:53:52","competition_id": "gpxwrxlhdgryk0j","competition_name": "Chinese U18 Women's National Games","home_team_id": "2y8m4zh8xwjql07","home_team_name": "Fujian U18 Women ","away_team_id": "8yomo4hvxg2q0j6","away_team_name": "Shandong U18 Women","match_time": "2021-05-03 15:00:00","match_tsp": 1620025200,"created_at": "2021-05-04 14:33:05"
}
$data = DB::connection('mongodb_football')->collection('match_list')->raw(function ($collection) {
return $collection->aggregate([
[
'$bucket' => [
'groupBy' => '$competition_id','boundaries' => ["4zp5rzgh3nq82w1","4zp5rzghjjgq82w","4zp5rzghkzq82w1","4zp5rzghpvnq82w","4zp5rzghx38q82w","4zp5rzghx5q82w1"],'default' => "Other",'output' => [
"data" => [
'$push' => [
"season_id" => '$season_id'
]
]
]
]
]
]);
});
输出:
需要根据competition_id
对所有数据进行分组,需要所有数据。
解决方法
- 从
groupBy
、boundaries
、default
和output
中删除 $ 前缀。
$bucket
'groupBy' 字段必须定义为以 $ 为前缀的路径或表达式
- 它说 group by field 需要引用字段,它应该以 $ 为前缀,但您已将其分配在数组括号 [] 中。
试试下面的语法,我还没有测试过,但会的,
$data = DB::connection('mongodb_football')->collection('match_list')->raw(function ($collection) {
return $collection->aggregate([
[
'$bucket' => [
'groupBy' => '$competition_id','boundaries' => ["4zp5rzgh3nq82w1","4zp5rzghjjgq82w","4zp5rzghkzq82w1","4zp5rzghpvnq82w","4zp5rzghx38q82w","4zp5rzghx5q82w1"],'default' => "Other",'output' => [
"data" => [
'$push' => [
"season_id" => '$season_id'
]
]
]
]
]
]);
});
,
解决方案
$data = DB::connection('mongodb_football')->collection('match_list')->raw(function ($collection) {
return $collection->aggregate([
[
'$bucket' => [
'groupBy' => '$competition_id','output' => [
"data" => [
'$push' => [
"season_id" => '$season_id'
]
]
]
]
]
]);
});