使用聚合框架,您需要运行具有以下阶段的管道,以便获得所需的结果:
db.collection.aggregate([
{ "$unwind": "$pb_event" },
{
"$group": {
"_id": {
"event_date": "$pb_event.event_date",
"event_type": "$pb_event.event_type"
},
"details": {
"$push": {
"_id": "$_id",
"name": "$Name"
}
},
"count": { "$sum": 1 }
}
},
{
"$group": {
"_id": "$_id.event_date",
"data": {
"$push": {
"event_type": "$_id.event_type",
"details": "$details",
"count": "$count"
}
}
}
},
{
"$project": {
"_id": 0,
"event_date": "$_id",
"data": 1
}
}
])
在上面的管道中,第一步是$unwind https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#pipe._S_unwind操作员
{ "$unwind": "$pb_event" }
当数据存储为数组时,这非常方便。当展开运算符应用于列表数据字段时,它将为应用展开的列表数据字段的每个元素生成一条新记录。它基本上使数据扁平化。
这是下一个管道阶段的必要操作,即$group https://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group通过解构对展平文档进行分组的步骤pb_event
数组字段event_date
and event_type
:
{
"$group": {
"_id": {
"event_date": "$pb_event.event_date",
"event_type": "$pb_event.event_type"
},
"details": {
"$push": {
"_id": "$_id",
"name": "$Name"
}
},
"count": { "$sum": 1 }
}
},
The $group https://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group管道运算符类似于 SQL 的GROUP BY
条款。在 SQL 中,您不能使用GROUP BY
除非您使用任何聚合函数。同样,您也必须使用 MongoDB 中的聚合函数(称为累加器运算符)。您可以阅读有关聚合函数的更多信息here https://docs.mongodb.com/manual/reference/operator/aggregation/group/#accumulator-operator.
In this $group https://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group操作,计算计数聚合的逻辑,即使用以下方法计算组中文档的总数$sum https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum累加器运算符。在同一个管道中,您可以聚合一个列表name
and _id
子文档通过使用$push https://docs.mongodb.com/manual/reference/operator/aggregation/push/#grp._S_push运算符返回每个组的表达式值数组。
前面的$group https://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group管道
{
"$group": {
"_id": "$_id.event_date",
"data": {
"$push": {
"event_type": "$_id.event_type",
"details": "$details",
"count": "$count"
}
}
}
}
将通过分组进一步聚合最后一个管道的结果event_date
,它通过使用创建新的数据列表来形成所需输出的基础$push https://docs.mongodb.com/manual/reference/operator/aggregation/push/#grp._S_push然后是决赛$project https://docs.mongodb.com/manual/reference/operator/aggregation/project/#pipe._S_project管道阶段
{
"$project": {
"_id": 0,
"event_date": "$_id",
"data": 1
}
}
通过重命名来重塑文档字段_id
字段到event_date
并保留其他字段。