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

MongoDB聚合查询:去重联系人并统计唯一错误码数量

MongoDB聚合:去重contactId后统计错误码数量

需求说明

  • 针对指定campId,去除同一contactId的重复记录,仅保留每个contactId最新的communicationValidationError
  • 最终统计各类错误码的出现次数

问题重现

当前使用的聚合语句未实现contactId去重,导致同一contactId的多条记录被重复统计(示例中错误计数显示为2而非1):

db.myCollection.aggregate([
    { $project: { _id: 0, campId: 1, contactId: 1, communicationValidationError: 1 } },
    { $sort: { "contactedOnTime.numberLong":-1}},
    { $match: { campId: '61baef7817cd8ff66518' } },
    { $group: { _id: { communicationValidationError: '$communicationValidationError' }, totalErrors: { $sum: 1 } } }
]).pretty()

原始数据示例

{
  "_id": { "$oid": "" }, 
  "campId": "61baef7817cd8ff66518", // camp1
  "contactId": "61aa6fbf77490b0007714273", // contact1
  "title": "Happy Holidays!",
  "communicationType": "EMAIL", 
  "contactedOnTime": { "$numberLong": "1695182032" }, // 时间1
  "communicationValidationError": "EMAIL_ADDRESS_NOT_PRESENT"
}

{
    "_id": { "$oid": "" },
    "campId": "61baef7817cd8ff66518", // camp1
    "contactId": "61aa6fbf77490b0007714273", // contact1
    "title": "Happy Holidays!",
    "communicationType": "EMAIL",  
    "contactedOnTime": { "$numberLong": "1695182074" }, // 时间2(最新)
    "communicationValidationError": "EMAIL_ADDRESS_NOT_PRESENT"
}

{
    "_id": { "$oid": "" },
    "campId": "61baef7817cd8ff66518", // camp1
    "contactId": "61aa6fbf77490b0007714274", // contact2
    "title": "Happy Holidays!",
    "communicationType": "EMAIL",
    "contactedOnTime": { "$numberLong": "1695182059" },
    "communicationValidationError": "EMAIL_BOUNCED"
}

正确聚合语句

db.myCollection.aggregate([
    // 1. 先过滤目标campId,减少后续处理数据量
    { $match: { campId: '61baef7817cd8ff66518' } },
    // 2. 按时间倒序排序,确保每个contactId的最新记录排在最前
    { $sort: { "contactedOnTime.numberLong": -1 } },
    // 3. 按contactId分组,仅保留每组第一条(最新)的错误码
    {
        $group: {
            _id: '$contactId',
            latestError: { $first: '$communicationValidationError' }
        }
    },
    // 4. 按错误码分组统计总次数
    {
        $group: {
            _id: '$latestError',
            totalErrors: { $sum: 1 }
        }
    },
    // 5. 重命名字段,让输出更直观
    {
        $project: {
            _id: 0,
            errorCode: '$_id',
            totalErrors: 1
        }
    }
]).pretty()

执行结果

针对示例数据,将得到符合预期的统计结果:

{ "errorCode" : "EMAIL_ADDRESS_NOT_PRESENT", "totalErrors" : 1 }
{ "errorCode" : "EMAIL_BOUNCED", "totalErrors" : 1 }

逻辑说明

  1. $match:优先过滤目标campId,避免处理无关数据,提升效率
  2. $sort:按contactedOnTime倒序排列,确保同一contactId的最新记录处于分组后的首位
  3. $group(按contactId):以contactId为分组键,用$first提取每组第一条记录的错误码,实现去重并保留最新错误
  4. $group(按错误码):对去重后的错误码进行计数统计
  5. $project:重命名字段,优化输出可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:26:01