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?
>Solution :
For cross-field comparison, you need $expr in the $match query.
The
$matchquery syntax is identical to the read operation query syntax; i.e.$matchdoes not accept raw aggregation expressions. To include aggregation expression in$match, use a$exprquery expression:
db.collection.aggregate([
{
$addFields: {
report_date: {
$dateFromString: {
dateString: "$date"
}
},
report_date3: {
$dateFromString: {
dateString: "2021-12-01"
}
}
}
},
{
$match: {
$expr: {
$eq: [
"$report_date",
"$report_date3"
]
}
}
}
])