Home > Net >  How do I match documents with timestamp greater than (now minus 1 hour and current minutes)?
How do I match documents with timestamp greater than (now minus 1 hour and current minutes)?

Time:11-04

I have the following documents:

{
    timestamp: 2022-11-03T15:00:00.000 00:00,
    ...
}

{
    timestamp: 2022-11-03T15:00:00.000 00:00,
    ...
}

{
    timestamp: 2022-11-03T10:00:00.000 00:00,
    ...
}

{
    timestamp: 2022-11-03T11:00:00.000 00:00,
    ...
}

If the time is 16:20, I'm trying to match only documents with a timestamp value greater than 15:00. So basically I'm trying to match on current time, minus one hour and the current minutes. How do I do that?

This is what I've tried:

{
    $match: {
        timestamp: {
            $gte: { 
                startDate: { 
                    $dateTrunc: { 
                        date: "$$NOW", 
                        unit: "hour" 
                    } 
                }, 
                unit: "hour",
                amount: 1
            }
        }
    }
}

But it doesn't return anything even though it's supposed to return two of the lines in the example.

CodePudding user response:

Try this:

db.collection.aggregate([
  {$match: {
      $expr: {
        $gte: [
          "$timestamp",
          {
            $dateAdd: {
              startDate: {$dateTrunc: {date: "$$NOW", unit: "hour"}},
              unit: "hour",
              amount: -1
            }
          }
        ]
      }
    }
  }
])

See how it works on the playground example

  • Related