Group by on a string doesn't work

Hi, I’m new to MongoDB 4.x and got stuck.
I’m using the PHP 8 MongoDB extension.

This is the document structure:

account_id (integer)
survey_id (integer)
answers (array)
0 (object)

1 (object)

Now I would like to group all questions so I only get the unique questions.
This is the code that I use:

$cursor = $collection->aggregate([
[ ‘$match’ => [ ‘account_id’ => 1005, ‘survey_id’ => 205244]],
[ ‘$unwind’ => ‘$answers.question’ ],
[ ‘$group’ => [’_id’ => ‘$answers.question’] ]

This however doesnt return any results. Also if I only unwind on $answers it doesnt work.
if I just use $answers on the unwind and group I do get back results, but they are not grouped/unique questions and questions only. So the group doesnt work and I should only get the questions back, not the answers. Thanks in advance!

Found the solution if anyone is interested:

$cursor = $collection->aggregate([
[ ‘$match’ => [ ‘account_id’ => …, ‘survey_id’ => …]],
[ ‘$project’ => [ ‘answers.question’ => 1] ],
[ ‘$unwind’ => ‘$answers’ ],
[ ‘$group’ => [’_id’ => ‘$answers.question’]]

Also used the wrong survey id.

I am pretty sure that

had nothing to do with having results. The real and only reason is

No, the unwind was incorrect

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.