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

MongoDB:按日期分组统计唯一玩家ID数量及总和

MongoDB按日期分组统计唯一用户数与总金额

需求说明

按集合中updatedAt字段的日期分组,统计每个日期对应的:

  • 唯一player.userId的数量
  • total字段的总和

示例数据

[
  {
    "_id": 1,
    "player" : {
        "userId": "unique_1"
    },
    "total": 100,
    "updatedAt": "2020-10-05"
  },
  {
    "_id": 2,
    "player" : {
        "userId": "unique_2"
    },
    "total": 200,
    "updatedAt": "2020-10-05"
  },
  {
    "_id": 3,
    "player" : {
        "userId": "unique_2"
    },
    "total": 200,
    "updatedAt": "2020-10-06"
  }
]

聚合查询命令

使用MongoDB聚合管道实现需求,代码如下:

db.collection.aggregate([
  {
    $group: {
      _id: "$updatedAt",
      userIds: { $addToSet: "$player.userId" },
      total: { $sum: "$total" }
    }
  },
  {
    $project: {
      _id: 1,
      uniquePlayers: { $size: "$userIds" },
      total: 1
    }
  }
])

命令解释

  1. $group阶段:

    • _id: "$updatedAt":指定按updatedAt日期作为分组依据
    • $addToSet: "$player.userId":将分组内的唯一userId收集到数组中(自动去重)
    • $sum: "$total":累加当前分组内所有文档的total值
  2. $project阶段:

    • $size: "$userIds":计算去重后的userId数组长度,得到唯一用户数并命名为uniquePlayers
    • 保留分组日期_id和累加后的total字段

执行结果

[
  {
    "_id": "2020-10-05",
    "uniquePlayers": 2,
    "total": 300
  },
  {
    "_id": "2020-10-06",
    "uniquePlayers": 1,
    "total": 200
  }
]

内容的提问来源于stack exchange,提问作者Oli Soproni B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:15:31