skip to Main Content

I’m using the MongoDB version 4.4, I’m trying to return the last documents inserted in the last 24 hous, and i need to run this query every day, because of this, i don’t set the date manualy, I need to use new Date()

The problem is, when a put more arguments to bring me the last 24 hours, the MongoDB return a error message to me, and i try for many ways to resolve this, but nothing worked

This is my code

{ 
    "$match" : { 
         "CreatedAt2" : { 
              "$gte" : ISODate("2022-04-21")
          }
     }
}

If i run this code, this works fine, but if a change the string by new Date(), the problem start.

In my test, if a put only new Date() like bellow and find by ‘$lte’, the code rans good.

‘$lte’ is only to check if new Date() will works

"CreatedAt2" :  {  $lte: new Date() }

So, if a tried to include the value to return the last 24 hours, my query don’t work, look bellow

"CreatedAt2" :  {  $gte: new Date(new Date().getTime() - 86400000) }

The MongoDB bring to me this error message

error message

Now I don’t know what I need to do to fix this.

3

Answers


  1. Try this

    "createdAt2":{$gte:new Date(Date.now() - 86400)
    

    This should work fine

    Login or Signup to reply.
  2. Consider leveraging the $$NOW aggregation variable and $subtract it by 24hours * 60minutes * 60 seconds * 1000 milliseconds = 86400000 ms to get the records within 24 hours

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $gte: [
              "$CreatedAt2",
              {
                "$subtract": [
                  "$$NOW",
                  86400000
                ]
              }
            ]
          }
        }
      }
    ])
    

    Here is the Mongo playground for your reference.

    Login or Signup to reply.
  3. Instead of subtracting 86400000 Milliseconds, you can also use

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $gte: [
              "$CreatedAt2",
              {
                 $dateSubtract: {
                    startDate: "$$NOW",
                    unit: "hour",
                    amount: 24
                 }
               }     
            ]
          }
        }
      }
    ])
    

    Or use a 3rd party date-library, e.g. moment.js

    { 
        "$match" : { 
             "CreatedAt2" : { 
                  "$gte" : moment().subtract(24, 'hours').toDate()
              }
         }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search