Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    $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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading