[英]How to filter mongodb collection using date field?
I have date string like this我有这样的日期字符串
'2021-03-09'
And my mongodb collection like this我的 mongodb 收藏是这样的
{
"_id": {
"$oid": "633aede250625c10dddfd57b"
},
"title": "test 1",
"description": "Hello World",
"date": {
"$date": "2021-03-09T18:30:00.000Z"
},
"image": "fd16b297-9ad1-4e84-8c3e-715a33b351b3.png",
"createdAt": {
"$date": "2022-10-03T14:12:50.399Z"
},
"updatedAt": {
"$date": "2022-10-03T14:12:50.399Z"
},
"__v": 0
},
{
"_id": {
"$oid": "633aede650625c10dddfd57f"
},
"title": "test 2",
"description": "Hello World",
"date": {
"$date": "2022-03-09T18:30:00.000Z"
},
"image": "2084f157-6610-402d-9dca-6681fe6da7d4.png",
"createdAt": {
"$date": "2022-10-03T14:12:54.982Z"
},
"updatedAt": {
"$date": "2022-10-03T14:12:54.982Z"
},
"__v": 0
}
I need filter and get the document by date field, and I tried follow the query like我需要过滤并按日期字段获取文档,我尝试按照查询进行操作
return db.eventsCollection.find({
date: date,
}).catch((err: Error) => {
logger.error(err);
return null;
});
But I couldn't get the results.但是我无法得到结果。
Try to filter using a range of dates (today and tomorrow);尝试使用日期范围(今天和明天)进行过滤;
const today = new Date(date);
const tomorrow = new Date(date);
tomorrow.setDate(tomorrow.getDate() + 1);
return db.eventsCollection.find({
date: { $gte: today , $lt: tomorrow }
}).catch((err: Error) => {
logger.error(err);
return null;
});
As you are given a date string as input, it would be more sensible to use $dateToString
to convert your date
into a date string for comparison.当您得到一个日期字符串作为输入时,使用
$dateToString
将您的date
转换为日期字符串以进行比较会更明智。
db.collection.find({
$expr: {
$eq: [
{
"$dateToString": {
"date": "$date",
"format": "%Y-%m-%d"
}
},
// your input here
"2021-03-09"
]
}
})
Here is the Mongo Playground for your reference.这是Mongo Playground供您参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.