Reputation: 6820
So for some reason Mongodb has stored date as Epoch 1593236606706
However now I need to query it. because I need to get the month and year from each of these.
I am wondering how do you ask mongodb to convert Epoch to Date?
I am trying the following
{ $convert: { input: "history.starttime", to: "date" } }
I have also tried
$addField:{
convertedDate: { $toDate: "$history.starttime" }
}
but no I think because I am not able to call the sub array?
Also tried this
{
history:{
convertedDate: { $toDate:"$history[starttime]" }
}
}
but that just puts it in the correct sub array - still can't grab start date from that subarray
Upvotes: 0
Views: 796
Reputation: 550
Example: https://mongoplayground.net/p/sNG9Wh2HeI4
You need to $unwind your array first and then do the conversion. Regroup it at the end
Upvotes: 1
Reputation: 22974
db.collection.aggregate([
{
"$unwind": "$history"
},
{
"$project": {
"d": {
$convert: {
input: "$history.key",
to: "date"
}
}
}
}
])
You need to have it part of $project
after unwinding
it as it is an array.
You can regroup it after project if you want to bring the original structure using $group
.
Upvotes: 1