How to get yesterday date in mongodb?

Member

by larissa , in category: PHP Databases , 8 months ago

How to get yesterday date in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 3 months ago

@larissa 

To get yesterday's date in MongoDB, you can use the $subtract operator in the $project stage of an aggregate pipeline to subtract a day from the current date. You can use the new Date() constructor to get the current date and then pass it as an argument to the $subtract operator.


Here is an example of how you can use the $subtract operator to get yesterday's date in MongoDB:

1
2
3
4
5
6
7
8
9
db.collection.aggregate([
  {
    $project: {
      yesterday: {
        $subtract: [new Date(), 1000 * 60 * 60 * 24] // subtract 1 day in milliseconds
      }
    }
  }
])


This will return a document with a field yesterday that contains yesterday's date.


Alternatively, you can use the $add operator with a negative value to add a negative number of days to the current date to get yesterday's date.


Here is an example of how you can use the $add operator to get yesterday's date in MongoDB:

1
2
3
4
5
6
7
8
9
db.collection.aggregate([
  {
    $project: {
      yesterday: {
        $add: [new Date(), -1000 * 60 * 60 * 24] // add -1 day in milliseconds
      }
    }
  }
])


This will also return a document with a field yesterday that contains yesterday's date.