TheStranger
TheStranger

Reputation: 1587

How do I get the full hour before the latest in MongoDB?

I'm trying to get the second latest full hour. So if the time is 15:30 now, I'm trying to get 14:00, so I basically need to truncate the current minutes and then furthermore truncate an hour..

I'm trying to project the date like this:

// Let's say the current time is 15:46
"period": {
    "start": 2022-11-03T14:00:00.000,
    "end": 2022-11-03T15:00:00.000
}

It's gonna be something like this:

{
   $project: {
        period: {
start: {
  "$subtract": [ {
    $hour: {
      "$toDate": "$$NOW"
    }
  }, 1 ]
},
end: {
  "$subtract": [ {
    $hour: {
      "$toDate": "$$NOW"
    }
  }, 1 ]
},

} }

How do I do that?

Upvotes: 0

Views: 29

Answers (2)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59503

Do you mean this one?

db.collection.aggregate([
  {
    "$project": {
        start: {
          $dateSubtract: {
            startDate: { $dateTrunc: { date: "$$NOW", unit: "hour" } },
            unit: "hour",
            amount: 1
          }
        },
        end: { $dateTrunc: { date: "$$NOW", unit: "hour" } }
  }
])

Upvotes: 1

wardialer
wardialer

Reputation: 492

I'm not sure i understood well... But, in case, maybe something like this?

https://mongoplayground.net/p/9xALfPpdSdS

db.collection.aggregate([
  {
    "$project": {
      hour: {
        "$subtract": [
          {
            $hour: {
              "$toDate": "$period.start"
            }
          },
          1
        ]
      }
    }
  },
  
])

Upvotes: 0

Related Questions