How to query documents at a specific date in Mongoose

In MongoDB, Date objects are stored in Unix timestamp format representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

Let us say that we have the following Task model in Mongoose:

const mongoose = require('mongoose')

const Task = mongoose.model('Task', { dueDate: Date })

To find all the tasks that belong to last month, you need to query for the start and end of the last month as shown below:

const start = new Date(2022, 6, 1) // 1st July, 2022
const end = new Date(2022, 6, 31) // 31 July, 2022

const tasks = await Task.find({
  dueDate: {
    $gte: start,
    $lte: end
  }
})

$gte and lte are comparison operators in MongoDB to select documents where the field value is between specific values.

For more accurate start and end dates, I suggest to use the date-fns utility library instead:

const { startOfDay, endOfDay } = require('date-fns')

const start = new Date(2022, 6, 1)
const end = new Date(2022, 6, 31)

const tasks = await Task.find({
  dueDate: {
    $gte: startOfDay(start),
    $lte: endOfDay(end)
  }
})

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.