Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match dates in MongoDB aggregation?

I have data like this:

[
  {
    date: "2021-12-01 00:00:00.0",
    
  },
  {
    date: "2021-12-02 00:00:00.0",
    
  }
]

I am trying to see if it matches a date that is stored in a string. My query is:

db.collection.aggregate([
  {
    $addFields: {
      report_date: {
        $dateFromString: {
          dateString: "$date"
        }
      },
      report_date3: {
        $dateFromString: {
          dateString: "2021-12-01"
        }
      }
    }
  },
  {
    $match: {
      report_date: "$report_date3"
    }
  }
])

But this is not returning any documents. How do I match this string with the date?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For cross-field comparison, you need $expr in the $match query.

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:

db.collection.aggregate([
  {
    $addFields: {
      report_date: {
        $dateFromString: {
          dateString: "$date"
        }
      },
      report_date3: {
        $dateFromString: {
          dateString: "2021-12-01"
        }
      }
    }
  },
  {
    $match: {
      $expr: {
        $eq: [
          "$report_date",
          "$report_date3"
        ]
      }
    }
  }
])

Sample Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading