laravel對Mongodb嵌套文檔執行分組查詢

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
                        ],
                    ]
                ]
            ]);
        });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章