【发布时间】:2021-08-26 11:05:30
【问题描述】:
所以我目前正在尝试从集合中获取数据并按年份和类型对其进行分组,
{
$group: {
_id: {
year: { $dateToString: { format: "%Y", date: "$date" } },
typeId: "$type",
},
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
"$_id.year": {
$push: {
_id: "$_id.typeId",
typeCount: "$count",
},
},
},
},
无论如何,我在项目的字段名称中使用$ 时遇到错误,因为我想将结果作为键值数组排序:
years[year]: {
count: num,
typeId: String
}
提前致谢:D
【问题讨论】:
-
我认为,您仍然需要使用第一次分组时的
year值进行第二次分组。然后,您可以使用该结果来获得所需的输出。
标签: mongodb mongoose aggregation-framework