Home > Blockchain >  How to add minutes in date on a MongoDB query
How to add minutes in date on a MongoDB query

Time:08-12

Suppose I have this document:

[
    {
        uuid: 1234,
        start: '2022-08-11T16:00:40 08:00',
        end: '2022-08-11T16:20:40 08:00'
    }
]

How do I get the documents that has a start value in between current date and current date 30 minutes

This is my current query but it isn't working:

{
    start: {
        $gte: new Date(),
        $lte: {
            $dateAdd: {
                startDate: new Date(),
                unit: 'minute',
                amount: 30
            }
        }
    }
}

CodePudding user response:

$dateAdd is an aggregation expression so in order to use it within the query language it must be wrapped with an $expr, like so:

db.collection.find({
  $expr: {
    $and: [
      {
        $gte: [
          "$start",
          "$$NOW"
        ]
      },
      {
        $lte: [
          "$start",
          {
            $dateAdd: {
              startDate: "$$NOW",
              unit: "minute",
              amount: 30
            }
          }
        ]
      }
    ]
  }
})

Mongo Playground

  • Related