我有以下文件;
{
"_id" : ObjectId("5b85312981c1634f59751604"),
"date" : "0"
},
{
"_id" : ObjectId("5b85312981c1634f59751604"),
"date" : "20180330"
},
{
"_id" : ObjectId("5b85312981c1634f59751604"),
"date" : "20180402"
},
{
"_id" : ObjectId("5b85312981c1634f59751604"),
"date" : "20180323"
},
我正在使用MongoDB 3.4
,我想使用date
的格式将ISODate
转换为year-month-day
,并且0
将产生1970-01-01
,结果将如下所示,
"date" : ISODate("1970-01-01")
"date" : ISODate("2018-03-30")
"date" : ISODate("2018-04-02")
"date" : ISODate("2018-03-23")
答案 0 :(得分:1)
您可以在Aggregation下使用
db.documents.aggregate([{
$addFields: {
year: { $toString: {
$trunc: { $divide: [{ $toInt: '$date' }, 10000] } }
},
month: {
$toString: {
$trunc: { $divide: [{ $mod: [{ $toInt: '$date' }, 10000] }, 100] }
}
},
day: {
$toString: {
$trunc: { $mod: [{ $toInt: '$date' }, 100] }
}
}
}
},
{
$project: {
_id: 0,
date: {
$toDate: {
$cond: [
{ $ne: ['$year', '0'] },
{ $concat: ['$year', '-', '$month', '-', '$day'] },
new Date("")
]
}
}
}
}
])
如果您有任何想法将日期“ YYYYMMDD”字符串转换为年(“ YYYY”),月(“ MM”) ,天(“ DD”),那么我们可以使其更简单