You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP 8.1+MongoDB统计分组重复用户数据异常问题

解决MongoDB嵌套数组分组统计重复用户的问题

你的问题核心是未先展开嵌套的usuarios数组,直接对包含数组的文档分组会导致统计逻辑完全错误。以下是修正后的聚合方案及PHP实现代码:

核心处理步骤

  1. 拆解嵌套数组:用$unwind将usuarios数组中的每个用户元素拆分为独立文档,确保单个用户信息单独参与统计
  2. 过滤无效数据(可选):提前剔除证件类型或证件号为空的无效用户记录,避免干扰统计结果
  3. 分组统计次数:按tipoDocumentoIdentificacion和numDocumentoIdentificacion的组合字段分组,累加重复次数
  4. 筛选目标记录:过滤出重复次数≥2的结果
  5. 格式化输出(可选):将结果整理为直观易读的格式

PHP 8.1 实现代码

<?php
require 'vendor/autoload.php';

// 初始化MongoDB客户端,替换为你的连接地址
$client = new MongoDB\Client("mongodb://localhost:27017");
// 替换为你的数据库名和集合名
$collection = $client->tu_base_de_datos->tu_coleccion;

$pipeline = [
    // 拆解usuarios数组,每个元素生成独立文档
    ['$unwind' => '$usuarios'],
    // 过滤掉证件信息为空的无效记录
    [
        '$match' => [
            'usuarios.tipoDocumentoIdentificacion' => ['$ne' => null],
            'usuarios.numDocumentoIdentificacion' => ['$ne' => null]
        ]
    ],
    // 按证件类型+证件号分组,统计重复次数
    [
        '$group' => [
            '_id' => [
                'tipo' => '$usuarios.tipoDocumentoIdentificacion',
                'num' => '$usuarios.numDocumentoIdentificacion'
            ],
            'count' => ['$sum' => 1]
        ]
    ],
    // 筛选重复次数≥2的记录
    ['$match' => ['count' => ['$gte' => 2]]],
    // 格式化输出字段,让结果更直观
    [
        '$project' => [
            '_id' => 0,
            'usuario' => ['$concat' => ['$_id.tipo', '$_id.num']],
            '重复次数' => '$count'
        ]
    ]
];

// 执行聚合查询
$result = $collection->aggregate($pipeline);

// 遍历输出结果
foreach ($result as $item) {
    echo $item['usuario'] . ' ' . $item['重复次数'] . PHP_EOL;
}
?>

关键注意点

  • $unwind是必选步骤:跳过这一步的话,分组会基于原始父文档而非数组内的单个用户,统计结果必然异常
  • 组合字段分组:必须将tipoDocumentoIdentificacion和numDocumentoIdentificacion作为$group的_id组合,才能准确识别同一用户
  • 提前过滤无效数据:避免空值或无效证件被统计,提升结果准确性

内容的提问来源于stack exchange,提问作者Alexander Ceballos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:54:57