[英]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?如何将此字符串与日期匹配?
For cross-field comparison, you need $expr
in the $match
query.对于跨字段比较,您需要在$match
查询中使用$expr
。
The
$match
query syntax is identical to the read operation query syntax;$match
查询语法与读操作查询语法相同; ie$match
does not accept raw aggregation expressions.即$match
不接受原始聚合表达式。 To include aggregation expression in$match
, use a$expr
query expression:要在$match
中包含聚合表达式,请使用$expr
查询表达式:
db.collection.aggregate([
{
$addFields: {
report_date: {
$dateFromString: {
dateString: "$date"
}
},
report_date3: {
$dateFromString: {
dateString: "2021-12-01"
}
}
}
},
{
$match: {
$expr: {
$eq: [
"$report_date",
"$report_date3"
]
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.