Home > Software engineering >  String to Date conversion and comparing it with today's date
String to Date conversion and comparing it with today's date

Time:07-26

My MongoDB looks something like this :

{"_id": "1234aa", "maturity_dt":"2022-07-10", "countryCode":"BLG"},
{"_id": "123ab", "maturity_dt":"2022-07-30", "countryCode":"BLG"}

Note that maturity_dt is a string. I want to fetch the records with maturity_dt greater than Today's date. Please help me build a query with aggregation. Since I have million records I cannot user foreach or any looping.

CodePudding user response:

Depending on your mongo engine you are using in python you will need to format your query something like:

maturity_dt__ge=datetime.datetime.today().strftime('%Y-%m-%d')

I would also make maturity_dt an index in your database.

CodePudding user response:

You can perform the comparison with $toDate and $expr. Use $$NOW to reference today's date.

db.collection.find({
  $expr: {
    $gt: [
      {
        "$toDate": "$maturity_dt"
      },
      "$$NOW"
    ]
  }
})

Here is the Mongo Playground for your reference.


If an aggregation pipeline must be used, you can do like below:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            "$toDate": "$maturity_dt"
          },
          "$$NOW"
        ]
      }
    }
  }
])

Here is the Mongo Playground for your reference.

  • Related