Last active
July 8, 2023 15:39
-
-
Save webarthur/7dd1827a98aecd8224316ea33716d807 to your computer and use it in GitHub Desktop.
7 methods to query between dates in MongoDB using the greater than ($gte) operator and the less than ($lt) operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let docs | |
// METHOD 1 - new Date() +1 day | |
const startDate = new Date('2021-03-31 00:00') | |
const endDate = new Date(startDate.getTime() + 86400000) | |
docs = await collection.find({ | |
date1: { | |
$gte: startDate, | |
$lt: endDate | |
} | |
}).toArray() | |
console.log('method 1', docs.length) | |
// METHOD 2 - dayjs: startOf/endOf | |
docs = await collection.find({ | |
date1: { | |
$gte: dayjs('2021-03-31').startOf('day').toDate(), | |
$lt: dayjs('2021-03-31').endOf('day').toDate() | |
} | |
}).toArray() | |
console.log('method 2', docs.length) | |
// METHOD 3 - timestamp | |
docs = await collection.find({ | |
date1: { | |
$gte: new Date(dayjs('2021-03-31 00:00').unix() * 1000), | |
$lt: new Date(dayjs('2021-03-31 23:59').unix() * 1000) | |
} | |
}).toArray() | |
console.log('method 3', docs.length) | |
// METHOD 4 - dayjs: Exact time | |
docs = await collection.find({ | |
date1: { | |
$gte: dayjs('2021-03-31 00:00').toDate(), | |
$lt: dayjs('2021-03-31 23:59').toDate() | |
} | |
}).toArray() | |
console.log('method 4', docs.length) | |
// METHOD 5 - new Date() extact time | |
const startDate2 = new Date('2021-03-31 00:00') | |
const endDate2 = new Date('2021-03-31 23:59') | |
docs = await collection.find({ | |
date1: { | |
$gte: startDate2, | |
$lt: endDate2 | |
} | |
}).toArray() | |
console.log('method 5', docs.length) | |
// METHOD 6 - dayjs: add +1 day | |
docs = await collection.find({ | |
date1: { | |
$gte: dayjs('2021-03-31').toDate(), | |
$lt: dayjs('2021-03-31').add(1, 'day').toDate() | |
} | |
}).toArray() | |
console.log('method 6', docs.length) | |
function getDateRange (dt1, dt2=dt1) { | |
const startDate = new Date(dt1 + ' 00:00') | |
const endDate = new Date(new Date(dt2 + ' 00:00').getTime() + 86400000) | |
return { | |
$gte: startDate, | |
$lt: endDate | |
} | |
} | |
// METHOD 7 - custom function with new Date() | |
docs = await collection.find({ | |
date1: getDateRange('2021-03-31') | |
}).toArray() | |
console.log('method 7', docs.length) | |
console.log(dayjs('2021-03-31 00:00').toISOString()) | |
console.log(new Date('2021-03-31 00:00').toISOString()) | |
console.log(new Date('2021-03-31').toISOString()) // There is a difference here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment