RussellHarrower
RussellHarrower

Reputation: 6820

Mongodb date stored as Epoch

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" } }

MongodB Data

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

Answers (2)

Koodies
Koodies

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

Gibbs
Gibbs

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.

playground

You can regroup it after project if you want to bring the original structure using $group.

Upvotes: 1

Related Questions