【问题标题】:How to rename a field when get distinct values with PHP and MongoDB?使用 PHP 和 MongoDB 获取不同值时如何重命名字段?
【发布时间】:2025-12-30 22:25:11
【问题描述】:

我的环境是 php5.6、MongoDB 4.0.13 和 mongo 驱动程序 1.6.16,假设我有来自数据库 db_x 的集合/表 table_x,如下所示:

    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

我想得到不同的code_y 值,我使用下面的代码,输出等于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;
}

但我的预期输出低于 SQL 查询 select distinct code_y as dept from table_x

【问题讨论】:

  • 为什么需要这样做? distinct 返回一个值数组
  • 我可以将单个数组值转换为不同的数组值吗?
  • 不具有独特性。您可以使用聚合组和项目实现相同的目的
  • 嗨,我已经尝试过了,但项目不工作,它需要光标,我得到了肮脏的结果,而不是我需要的,你能告诉我相同的示例代码吗?非常感谢

标签: php mongodb distinct php-5.6


【解决方案1】:

最后,我使用下面的代码来获得重命名的字段。

$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]
        )
);

【讨论】:

    最近更新 更多