MongoDB-使用$match之间的日期



所以我尝试使用MongoDB$match来获取两个日期之间的数据,但结果数据没有返回。它看起来像什么:

db.collection.aggregate([
{
$match: {
date: {
$gte: new Date("2022-10-23"),
$lt: new Date("2022-10-25"),
},
}
},
{
$group: {
_id: "$title",
title: {
$first: "$title"
},
answer: {
$push: {
username: "$username",
date: "$date",
formId: "$formId",
answer: "$answer"
}
}
}
},
])

以下是我试图在Mongo操场上运行的数据:https://mongoplayground.net/p/jKx_5kZnJNz

我认为我的代码不再有错误了。。。但为什么它给出了一个空的回报。

将注释迁移到答案帖子中以获得完整的解释。

第1期

当您尝试与Date进行比较时,文档将date字段作为字符串类型包含,这会导致输出不正确。

请确保您正在以精确的类型比较这两个值。

date值迁移到Date类型或

通过$toDate将查询中的date字段转换为Date类型。

{
$match: {
$expr: {
$and: [
{
$gte: [
{
$toDate: "$date"
},
new Date("2022-10-23")
]
},
{
$lt: [
{
$toDate: "$date"
},
new Date("2022-10-25")
]
}
]
}
}
}

问题2

由于您使用的是$lt($lt: new Date("2022-10-25")(,因此它不会包括带有date: new Date("2022-10-25")的文档。

对于包含在内的结束日期,您应使用$lte

演示@Mongo Playground

最新更新