mongodb - 如何获取日期的年份并计算每年的记录
问题描述
我有一个 CSV 文件,如下所示:Name, Age, Date of Birth (M/D/Y as a string)
. 我想year
从'Date of Birth'
现场获得并计算每年的人数。结果应如下所示:
- 2005: 53
- 2006: 12
- 2007: 21
- ...
我试过这个,但没有用:
db.collection.aggregate({
$group: {
_id: { $year: "$Date of Birth" },
total: { $sum: 1 }
}
})
解决方案
这是因为$year
可以在日期上工作,但不能在字符串上工作,请试试这个:
db.collectionName.aggregate([{ $project: { _id: 0, 'Date of Birth': { $arrayElemAt: [{ $split: ["$Date of Birth", "/"] }, 2] } } },
{ $group: { _id: '$Date of Birth', total: { $sum: 1 } } }])
收集数据:
/* 1 */
{
"_id" : ObjectId("5e0d0924400289966eab31bf"),
"Date of Birth" : "01/01/2020"
}
/* 2 */
{
"_id" : ObjectId("5e0d092b400289966eab3349"),
"Date of Birth" : "01/11/2020"
}
/* 3 */
{
"_id" : ObjectId("5e0d0939400289966eab3696"),
"Date of Birth" : "11/01/2021"
}
/* 4 */
{
"_id" : ObjectId("5e0d0946400289966eab398e"),
"Date of Birth" : "11/01/2022"
}
/* 5 */
{
"_id" : ObjectId("5e0d094e400289966eab3bb0"),
"Date of Birth" : "11/01/2019"
}
结果 :
/* 1 */
{
"_id" : "2022",
"total" : 1.0
}
/* 2 */
{
"_id" : "2019",
"total" : 1.0
}
/* 3 */
{
"_id" : "2021",
"total" : 1.0
}
/* 4 */
{
"_id" : "2020",
"total" : 2.0
}
推荐阅读
- sql-server - 在 SQL Server 中将相似的字符串分组在一起
- html - 有没有办法在 Azure DevOps wiki 页面的 HTML 表中添加 Markdown 链接?
- python-3.x - 使用查询参数“q”过滤谷歌日历事件列表
- java - 按下后退按钮时禁用 Android 按钮
- google-cloud-platform - “condition_monitoring_query_language”的 Terraform 不支持块类型错误
- google-chrome - 如何检查浏览器插件是否与开发人员联系?
- javascript - 使用 Nodejs 时,SVG 标签有时不会出现
- c# - 使控件无法选择
- java - 如何分析单个 Java (Spring) 方法运行?
- c# - 带有泛型的可空引用的注释