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.