laravel使用laravel-mongoDB对嵌套文档执行分组查询
- $unwind将内嵌数组打散成单个文档
- $match相当与匹配条件
- $project相当于选取字段
- $group相当于分组,必须有一个_id字段代表每个组的标识,可以是单个字段,也可以是多个。比如按性别分组,_id就是性别
$res = Reply::raw(function ($collection) use ($que_id, $index) {
return $collection->aggregate([
[
'$unwind' => [
'path' => '$reply_list',
'includeArrayIndex' => 'arrayIndex'
]
],
[
'$match' => [
'arrayIndex' => $index,
'que_id' => $que_id
]
],
[
'$project' => [
'reply_list.issue_number' => 1,
'reply_list.iss_type' => 1,
'reply_list.content' => 1
]
],
[
'$unwind' => [
'path' => '$reply_list.content'
]
],
[
'$group' => [
'_id' => [
'content' => '$reply_list.content',
'type' => '$reply_list.iss_type'
],
'count' => [
'$sum' => 1
],
]
]
]);
});
本文介绍如何在Laravel中使用laravel-mongoDB包对包含嵌套数组的文档进行高级查询,包括使用$unwind打散数组、$match筛选条件、$project选择字段及$group进行分组统计。


被折叠的 条评论
为什么被折叠?



