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 } } ])
命令解释
$group阶段:
_id: "$updatedAt":指定按updatedAt日期作为分组依据$addToSet: "$player.userId":将分组内的唯一userId收集到数组中(自动去重)$sum: "$total":累加当前分组内所有文档的total值
$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.
相关产品推荐
相关产品推荐

