Reputation: 807
I am using the MongoDB aggregation framework to group, sort and project some stuff from my database. The element of my result array looks like the following
{
someField: "someField",
timestamp: "2017-12-05T19:00:00.000Z"
}
The aggregation pipeline step I struggle with looks like the following
{
$project: {
_id: 0,
someField: 1,
timestamp: '$_id.timestamp',
}
}
I want to convert that DateTime string into an ISODate. If I use ISODate('$timestamp')
the mongo client returns the error Invalid ISODate
.
Another approach was to use just Date('$timestamp')
, just returns the my local date as if I would be using Date()
. Nevertheless if I enter print(ISODate("2017-12-05T19:00:00.000Z"))
directly into the mongo client everything is working as expected.
Any suggestions?
EDIT: We're using Mongo 3.4. Version 3.6 offers a solution, but I am not sure if we can upgrade to 3.6. (See answer below)
Upvotes: 1
Views: 2650
Reputation: 75984
You can use the new $dateFromString
operator available in 3.6.
db.collection.aggregate([
{
"$project": {
"timestamp": {
"$dateFromString": {
"dateString": "$timestamp"
}
}
}
}
])
Upvotes: 1