Tried to get records from mongodb between including two days but in my code only i am getting between two days.
Example:
01-06-2020 to 08-06-2020 = getting reco
The answer on your other question should return the correct result. I'll also emphasise that it's better to store the date as date object.
Let's try another approach by using $dateFromString
on the input values as well.
tableReportdata.find({
$expr: {
$and: [
{
$gte: [
{
$dateFromString: {
dateString: "$todaydate",
format: "%d-%m-%Y",
timezone: "UTC"
}
},
{
$dateFromString: {
dateString: "01-06-2020",
format: "%d-%m-%Y",
timezone: "UTC"
}
}
]
},
{
$lte: [
{
$dateFromString: {
dateString: "$todaydate",
format: "%d-%m-%Y",
timezone: "UTC"
}
},
{
$dateFromString: {
dateString: "07-06-2020",
format: "%d-%m-%Y",
timezone: "UTC"
}
}
]
}
]
}
}, function(err, docs) {
if (err) {
console.log(err);
return;
} else {
console.log("Successful loaded report data");
res.json({ data: docs, msg: 'Report data loaded.' });
}
});
Shorter version with a helper function
const dateUTCexpr = (dateString) => ({
$dateFromString: {
dateString,
format: "%d-%m-%Y",
timezone: "UTC"
}
})
tableReportdata.find({
$expr: {
$and: [
{
$gte: [dateUTCexpr("$todaydate"), dateUTCexpr("01-06-2020")]
},
{
$lte: [dateUTCexpr("$todaydate"), dateUTCexpr("07-06-2020")]
}
]
}
}, function(err, docs) {
if (err) {
console.log(err);
return;
} else {
console.log("Successful loaded report data");
res.json({ data: docs, msg: 'Report data loaded.' });
}
});
If you have todaydate
defined as String
in your schema, also make sure that it's properly converted in your database, you can use the following code
const dateUTCexpr = (dateString) => ({
$dateFromString: {
dateString,
format: "%d-%m-%Y",
timezone: "UTC"
}
})
tableReportdata.find({
todaydate: {
$gte: dateUTCexpr("01-06-2020"),
$lte: dateUTCexpr("07-06-2020")
}
}, function(err, docs) {
if (err) {
console.log(err);
return;
} else {
console.log("Successful loaded report data");
res.json({ data: docs, msg: 'Report data loaded.' });
}
});