mongodb - 在MongoDB中以字符串格式的日期按月和年分组
问题描述
我收藏的日期是字符串格式。我正在尝试按月和年对值进行分组。我试过$toDate
和$dateFromString
. 当我尝试$month
and$year
时,我会得到一些1
月份和随机年份的年份。
我不知道接下来我应该做什么。如何按月和年分组?
这是我的代码:
db.hb_data.aggregate([{
$match: {
date: {$exists: true}
}
}, {
$group: {
_id: {date: "$date"},
video_starts:{$sum: '$video_starts'}
}
}, {
$project: {
month: { $month: new Date("$_id.date") } ,
year: { year: new Date("$_id.date") } ,
date: "$_id.date",
video_starts: '$video_starts'
} }
])
这是我的结果:
当我的日期为字符串格式时,如何按月和年获得总和?
解决方案
假设这是数据集。
[
{"Id_Cust": "4145","firstName": "Albade","lastName": "Maazou", "gender": "female","date": "21/03/1981"},
{"Id_Cust": "5296", "firstName": "Rafael","lastName": "Oliveira","gender": "male","date": "08/06/1987"},
{"Id_Cust": "6192","firstName": "Abdul Rahman","lastName": "Budjana","gender": "male","date": "26/01/1990"}
]
您可以通过$dateFromString
以下方式使用它:
db.collection.aggregate([
{
$project: {
month: {
$month: {
$dateFromString: {
dateString: "$date",
format: "%d/%m/%Y"
}
}
},
year: {
$year: {
$dateFromString: {
dateString: "$date",
format: "%d/%m/%Y"
}
}
}
}
},
])
输出:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"month": 3,
"year": 1981
},
{
"_id": ObjectId("5a934e000102030405000001"),
"month": 6,
"year": 1987
},
{
"_id": ObjectId("5a934e000102030405000002"),
"month": 1,
"year": 1990
}
]
更新
您也可以使用$toDate
但您的字符串日期格式应该是 "yyyy-mm-dd"
格式,例如{$toDate: "2018-03-03"}
db.collection.aggregate([
{
$project: {
month: {
$month: {
$toDate: "$date"
}
},
year: {
$year: {
$toDate: "$date"
}
}
}
}
])
它提供与上面完全相同的输出,但请确保您的字符串日期是"yyyy-mm-dd"
这种格式。
推荐阅读
- python - Python IDLE 的绘图问题
- flutter - flutter_pagewise 库在切换时不保留页面(滚动)状态
- javascript - 在列表列表中向下弯曲嵌套对象
- c++ - C++ Stack Overflow 是什么原因造成的?
- html - 如何定位哪个包含?(不包含)?
- java - 如何遍历 .txt 文件并将结果存储在 2d arrayList 中
- ios - 在 ios Flutter 上实现 Firebase 匿名身份验证
- c# - 如何向上导航几个文件夹
- android - 如何使android studio按创建日期显示项目目录中的文件
- reactjs - 依赖数组中的对象属性时不触发useEffect