Home > database >  How to match dates in MongoDB aggregation?
How to match dates in MongoDB aggregation?

Time:01-05

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?

CodePudding user response:

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

  •  Tags:  
  • Related