[
{
_id:1 value: "8 Aug 2022, 1:13 PM"
},
{
_id:2 value: "15 Aug 2022, 1:13 PM"
}
]
Want to convert the above documents with the value field as an ISO Date
I was splitting the first part with $split with space as delimitter and then trying to rearrange the value(stuck here) and from a date from $dateFromString
My approach:
db.collection.aggregate([
{
"$project": {
value: {
"$split": [
"$value",
","
]
}
}
},
{
"$set": {
"value": {
"$arrayElemAt": [
"$value",
0
]
}
}
},
{
"$project": {
value: {
"$split": [
"$value",
" "
]
}
}
},
])
which got the result
[
{
"_id": ObjectId("5a934e000102030405000000"),
"value": [
"8",
"Aug",
"2022"
]
},
{
"_id": ObjectId("5a934e000102030405000001"),
"value": [
"15",
"Aug",
"2022"
]
}
]
Want this to be converted to ISO Date
2
Answers
You can do this in several different ways, here is one example using $dateFromParts, The only issue is you have to manually convert months names to the months number, I did this using
$switch
, like so:Mongo Playground
As you can see I left a todo for you to add all the other cases to the
$switch
condition.Query
$dateFromParts
, theyear/month/hour/minute
the month is taken as index of the array that has the months as strings
$unset
them*i don’t know if there is simpler way, but you have pm also, and also month is in string, we have
$dateFromString
alsoPlayMongo (put the mouse at the end of each stage to see what it produces)