Home > other >  how to add comparision for current date and time in mongdb views
how to add comparision for current date and time in mongdb views

Time:05-31

Here In my current SQL query there is now() function which gives current data and time, I have to use similar function in mongo DB view query to use function which gives current date and time. Can anyone please tell me which function and how to use that function in mongo DB view?

When I have tried both, If I use new ISODate() then it is giving me error like ISODate is not defined, when I tried with new Date(), then view is creating but I am not able to open the view. I have compare one field with less than current time

CodePudding user response:

As I understand you are trying to build a view in MongoDB which requires a date comparison.

To do this MongoDB has some system variables you can use in your aggregation pipeline. You can use $$NOW variable to compare any field with current timestamp.

There is one catch here. $match does not accept raw aggregation expression. From the $match docs:

The $match query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions. To include aggregation expression in $match, use a $expr query expression:

As $$NOW is a system variable we need to use $expr:

Expressions can include field paths, literals, system variables, expression objects, and expression operators. Expressions can be nested.

Here is an example on how you can use $expr with $$NOW:

db.sample.aggregate([
  {
    "$match": {
      $expr: {
        $gte: [
          "$scheduleMessageTime",
          "$$NOW"
        ]
      }
    }
  }
])
  • Related