How to get yesterday date in mongodb?

Member

by larissa , in category: PHP Databases , 2 years ago

How to get yesterday date in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by samara , 2 years 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.

by elise_daugherty , a year ago

@larissa 

In MongoDB, you can use the $subtract operator along with the $millisecond date aggregation operator to get the date of the previous day.


Here's an example query to retrieve the date of yesterday:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
db.collection.aggregate([
  {
    $project: {
      yesterday: {
        $subtract: [
          { $toDate: "$dateField" }, // Replace "dateField" with your date field
          { $multiply: [86400000, 1] } // milliseconds in a day: 24 * 60 * 60 * 1000
        ]
      }
    }
  }
])


This query contains a $project stage that uses the $subtract operator to subtract the milliseconds of a day from the given date field. The $toDate operator converts the date field to a valid date object before performing the subtraction.


Remember to replace "dateField" with the name of your actual date field in your collection.