-1

My environment is php5.6, MongoDB 4.0.13 and mongo driver 1.6.16, and supposed I have collection/table table_x from database db_x as below:

    code_x   code_y      value        name   color
   ------------------------------------------------
1   00001    111         300           aa     1 
2   00001    222         100           bb     3
3   00002    111         200           cc     1
4   00002    444         400           dd     2
.....
99  00029    222         200           ee     3
100 00030    999         400           ff     1

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:

$res = $db_x->command(array("distinct"=>"table_x", "key"=>"code_y"));

foreach ($res['values'] as $idx) {
    $res[$idx]['_id'] = $idx;
}

but my expected output is below SQL query select distinct code_y as dept from table_x

Elsa
  • 1
  • 1
  • 8
  • 27
  • Why do you need to do that? distinct returns an array of values – Gibbs Aug 12 '20 at 03:04
  • Can I convert that single array values to different array value? – Elsa Aug 12 '20 at 04:17
  • Not with distinct. You can achieve the same using aggregate group and project – Gibbs Aug 12 '20 at 04:26
  • hi, I already tried, but project not works, and it needs cursor, I got dirty results, and not what i need, could you please show me same sample code? Thanks so much – Elsa Aug 12 '20 at 04:29

1 Answers1

0

Finally, I use the below code to get renamed fields.

$res = $db_x->command (
        array(
            "aggregate" => "table_x",
            "pipeline" =>
                array(
                    array( '$group' => array( "_id" => ['new_id' =>'$code_y', 'new_name' => '$code_x', 'new_color' => '$color']))),
            "cursor" => ['batchSize' => 200]
        )
);
Elsa
  • 1
  • 1
  • 8
  • 27