首页 > 解决方案 > 如何获取日期的年份并计算每年的记录

问题描述

我有一个 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 }
    }
})

标签: mongodb

解决方案


这是因为$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
}

推荐阅读