Mongodb 如何获取日期年份和每年的计数记录
我有一个CSV文件,如下所示:Mongodb 如何获取日期年份和每年的计数记录,mongodb,Mongodb,我有一个CSV文件,如下所示:姓名、年龄、出生日期(M/D/Y作为字符串)。我想从“出生日期”字段中获取年份,并计算每年的人数。结果应该如下所示: - 2005: 53 - 2006: 12 - 2007: 21 - ... 我试过这个,但没用: db.collection.aggregate({ $group: { _id: { $year: "$Date of Birth" }, total: { $sum: 1 } } }) 这是
姓名、年龄、出生日期(M/D/Y作为字符串)
。我想从“出生日期”字段中获取年份
,并计算每年的人数。结果应该如下所示:
- 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
}
结果:
/* 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
}
MongoDB存储BSON文档,而不是CSV文件。您的文档看起来怎么样?谢谢,它工作得很好。最后一个问题-如何使用sort()进行排序?@jaca777:请尝试在$group
阶段:{$sort:{total:-1}}}
之后添加此选项,其中-1
从高到低(Vs)1
从低到高。