I would like to get the distinct code_y
values, and I use below code, the output is equal to select distinct code_y from table_x
,
JavaScript
x
$res = $db_x->command (
array(
"aggregate" => "table_x",
"pipeline" =>
array(
array( '$group' => array( "_id" => ['id' =>'$code_y', 'name' => '$code_x', 'color' => '$color']))),
"cursor" => ['batchSize' => 200]
)
);
I got results as below, I don’t need [_id] => Array
, just id, name and color, How to separate array from nested arrays with MongoDB and PHP aggregate? Or how to put [_id] => Array
together with id, name and color
? as in my front-end htmls pages, I got [object] [Object]
because of those nested arrays.
JavaScript
[0] => Array
(
[_id] => Array
(
[id] => a1
[name] => bbb
[color] => blue
)
)
[1] => Array
(
[_id] => Array
(
[id] => a2
[name] => aaa
[color] => blue
)
)
[2] => Array
(
[_id] => Array
(
[id] => a3
[name] => abc
[color] =>red
)
)
What I want is as below:
JavaScript
[0] => Array
(
[id] => a1
[name] => bbb
[color] => blue
)
[1] => Array
(
[id] => a2
[name] => aaa
[color] => blue
)
[2] => Array
(
[id] => a3
[name] => abc
[color] =>red
)
Advertisement
Answer
What you need is a another stage after the group.
You could either use project and list each field:
JavaScript
array( '$project' => array(
"id" => '$_id.id',
"name" => '$_id.name',
"color" => '$_id.color'
))
or $replaceRoot
to grab them all:
JavaScript
array( '$replaceRoot' => array( "newRoot" => '$_id' ))