Home > Software engineering >  MongoDB select last documents in 24 hours
MongoDB select last documents in 24 hours

Time:05-02

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.

CodePudding user response:

Try this

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

This should work fine

CodePudding user response:

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.

  • Related