gpt4 book ai didi

node.js - 日期过滤在 mongodb 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:21 25 4
gpt4 key购买 nike

您能告诉我如何在 MongoDB 中按日期参数过滤数据吗?我喜欢这个 https://mongoplayground.net/p/72LzlP1Sr5W

db.collection.find({
"Att Date": {
$gte: "2019-01-01",
$lte: "2019-01-31"
}
})

当前没有文档显示此查询

期待

[
{
"_id": ObjectId("5d84330c50d3e4083c7be27b"),
"Emp No": "A10088P2C",
"Emp Name": "MANISHA JHA",
"Card No": "2076",
"Department": "THBS",
"Att Date": "03-Jan-2019",
"In Time": "03-Jun-2019 10:53",
"Out Time": "03-Jun-2019 18:13",
"Status": "P ",
"Late By ": "01:53",
"Early By ": "00:00",
"Total Hour": "07:20",
"OT Hour": "00:00",
"Location": "Consolidated",
"id": "A10088P2C-03-Jun-2019"
},
{
"_id": ObjectId("5d84330c50d3e4083c7be27f"),
"Emp No": "A10088P2C",
"Emp Name": "MANISHA JHA",
"Card No": "2076",
"Department": "THBS",
"Att Date": "10-Jan-2019",
"In Time": "10-Jun-2019 10:32",
"Out Time": "10-Jun-2019 18:25",
"Status": "P ",
"Late By ": "01:32",
"Early By ": "00:00",
"Total Hour": "07:53",
"OT Hour": "00:00",
"Location": "Consolidated",
"id": "A10088P2C-10-Jun-2019"
},
{
"_id": ObjectId("5d84330c50d3e4083c7be284"),
"Emp No": "A10088P2C",
"Emp Name": "MANISHA JHA",
"Card No": "2076",
"Department": "THBS",
"Att Date": "17-Jan-2019",
"In Time": "17-Jun-2019 13:16",
"Out Time": "17-Jun-2019 18:25",
"Status": "P ",
"Late By ": "04:16",
"Early By ": "00:00",
"Total Hour": "05:09",
"OT Hour": "00:00",
"Location": "Consolidated",
"id": "A10088P2C-17-Jun-2019"
}
]

最佳答案

我建议(如评论中所述)将日期存储为文档中的日期对象,以有效地使用日期操作并避免转换。

要解决这种情况,您可以使用 $match聚合 , $addFields , $toDateISODate 转换。

db.collection.aggregate([
{
$addFields: {
formattedDate: {
$toDate: "$Att Date"
}
}
},
{
$match: {
formattedDate: {
$gte: ISODate("2019-01-01"),
$lte: ISODate("2019-01-31")
}
}
}
]);

注意:在 mongo Playground 上更新 link .

  1. $addFields 会将 Att Date 转换为 ISODate 并将其传递到下一阶段。
  2. $match 采用本质上是 Att DateformattedDate 并与传递的日期字符串进行比较(使用 ISODate转换)。
  3. 如果需要,您可以在下一阶段投影中使用 $project 删除该 formattedDate

关于node.js - 日期过滤在 mongodb 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com