mongodb - Mongodb 中的日期字段 - 按日期字段分组 ID 年份 - 聚合框架
问题描述
我在处理客户请求时遇到问题。我有以下数据:
{
"_id" : "6489",
"post_date" : ISODate("2014-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6490",
"post_date" : ISODate("2014-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6491",
"post_date" : ISODate("2014-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6492",
"post_date" : ISODate("2014-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6493",
"post_date" : ISODate("2015-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6494",
"post_date" : ISODate("2015-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6495",
"post_date" : ISODate("2016-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6496",
"post_date" : ISODate("2016-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6497",
"post_date" : ISODate("2016-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6498",
"post_date" : ISODate("2016-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6499",
"post_date" : ISODate("2016-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{
"_id" : "6500",
"post_date" : ISODate("2017-12-20T17:00:00.000+0000"),
"post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
我需要输出一个显示年份(posting_date)和帖子数量(_id)的表格。在 SQL 中,这将是计数 _id 和按发布日期(年份)进行的分组。
问题是posting_date 的格式,我必须从中提取年份。格式如下:
"post_date" : ISODate("0105-08-17T00:00:00.000+0000")
我已经写了一个代码,但它没有工作。这是我的代码:
db.posts.aggregate(
[
{
$project:
{
year: { $year: "$post_date" }
}
},
{
"$group" : {
"_id" : {
"post_date" : "$post_date"
},
"COUNT(_id)" : {
"$sum" : NumberInt(1)
}
}
},
{
"$project" : {
"_id" : NumberInt(0),
"COUNT(_id)" : "$COUNT(_id)",
"post_date" : "$_id.post_date"
}
},
{
"$sort" : {
"COUNT(_id)" : NumberInt(-1)
}
}
]
);
有没有人有想法或在我的代码中找到错误?我会很高兴得到帮助。输出应如下所示:
post_date number of posts
2014 4
2015 2
2016 5
2017 1
非常感谢,吉姆
解决方案
推荐阅读
- ionic-framework - 离子:如何修复 UnhandledPromiseRejectionWarning?
- mule - Mule 4 中的批处理
- jquery - jQuery - 如果 div 重叠调整 css 顶部值
- python - 在python中的指定html块之间提取文本
- testng - KotlinTest 是否也支持 TestNG?
- sequence - odoo 10 中的测序
- angular - 如何删除下划线并在有角材料组件周围提供一个框?
- openxlsx - 防止 writeDataTable (openxlsx) 写入任何列名
- angularjs - AngularJS 使用默认参数删除哈希 (#)
- c# - 将大型 3rd 方 dll 拆分为较小的部分