MongoDB PHP聚合-输出数组中的数据集不正确

时间:2019-02-14 09:34:35

标签: mongodb aggregate

我正在尝试从几个文档中选择数据并以嵌套数组的形式输出。 总计:

$aggBuilder = $this->documentManager->getDocumentCollection(User::class);

        $outputData = $aggBuilder->aggregate([
                ['$match' => [
                    '_id' => ['$in' => $usersId]
                    ]
                ],
            ['$unwind' => '$articles'],
            ['$lookup' => [
                'from' => 'articles',
                'localField' => 'articles._id',
                'foreignField' => '_id',
                'as' => 'article',
            ]],
            ['$unwind' => '$article'],
            ['$lookup' => [
                'from' => 'comments',
                'localField' => 'comments._id',
                'foreignField' => 'article_id',
                'as' => 'article.comment'
            ]],

            ['$group' => [
                '_id' => [
                    'id' => '$_id',
                    'name' => '$name',
                    'desc' => '$desc',
                ],
                'articles' => ['$addToSet' => [
                    'id' => '$article._id',
                    'title' => '$article.title',
                    'content' => '$article.content',
                    'comments' => ['id' => $article.comment.id', 'content' => '$article.comment.content'],
                ]],
            ]]
        ],
            [
                'cursor' => [
                    'batchSize' => 101,
                ],
            ]);
        dd($outputData->toArray());

问题的部分原因是我试图在每篇文章中收集这篇文章的评论。

某些原因输出看起来像这样:

'Andy Jones' = [
              'Article First' = [
                    'id' = 'sdgdf76g8df',
                    'title' = 'First Article'
                    'content' = 'Contetn of article'
                    'comments' = [
                          'id' = [
                              'dfdh54gdfter',
                              '32gdfhfgh43et',
                              '34te3gdfgerdt'
                          ],
                          'content' = [
                              'content for first article',
                              'content for second article',
                              'content for third article'
                          ]
                    ]
              ]

        ]

如您所见,注释分为两个数组。一个用于“ id”,一个用于“ content”。
我想要的是每个评论都独立的数组,而该数组中的数据来自单个评论。像下面这样:

'comments' = [
                          [0] = [
                              'id' = 'dfdh54gdfter',
                              'content' = 'Lorem ipsum 1',

                          ],
                          [1] = [
                              'id' = 'dfdg4554er',
                              'content' = 'Lorem ipsum 2',

                          ],
                          [2] = [
                              'id' = 'dfdh54gdfter',
                              'content' = 'Lorem ipsum 3',

                          ],
                    ]

谢谢。

0 个答案:

没有答案