skip to Main Content

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 lesser than Today’s date. Please help me build a query with aggregation. Since I have million records I cannot use foreach or any looping.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search